hex() function in Python - GeeksforGeeks (2024)

Last Updated : 26 Jul, 2023

Summarize

Comments

Improve

,The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form. Hexadecimal is a base-16 numbering system commonly used in computer science and programming. In this article, we will explore the hex() function and its usage in converting decimal numbers to hexadecimal format in Python.

Python Hex() Function Syntax

Syntax: hex(x)

Parameter: x – an integer number (int object)

Returns: Returns hexadecimal string.

Python Hex() Function Example

The hex() function in Python is used to convert a decimal number to its corresponding hexadecimal representation. It takes an integer as an argument and returns a string representing the hexadecimal value.

Python3

decimal_number = 999

hexadecimal_value = hex(decimal_number)

print(hexadecimal_value)

Output

0x3e7

Python Hex() FunctionFor ASCII and Float Value

In Python, we can use the hex() function to convert ASCII characters to their corresponding hexadecimal representation. The ord() function is used to get the ASCII value of a character, and then hex() is applied to convert that value to hexadecimal.

Python3

# Python3 program to illustrate

# hex() function

print("The hexadecimal form of 23 is "

+ hex(23))

print("The hexadecimal form of the "

"ascii value is 'a' is " + hex(ord('a')))

print("The hexadecimal form of 3.9 is "

+ float.hex(3.9))

Output

The hexadecimal form of 23 is 0x17
The hexadecimal form of the ascii value os 'a' is 0x61
The hexadecimal form of 3.9 is 0x1.f333333333333p+1

Python Hex() Function Perform Bitwise Operations

In Python we can use Hex() to perform bitwise operations. Bitwise operations are operations that manipulate individual bits within binary representations of data. Python provides various bitwise operations, such as AND, OR, XOR, NOT, etc.

Python3

hex_num1 = 0x22

hex_num2 = 0x0A

bitwise_and = hex_num1 & hex_num2

bitwise_or = hex_num1 | hex_num2

print(hex(bitwise_and))

print(hex(bitwise_or))

Output

0x2
0x2a

Python Hex() Function for Different Conversion

In Python, we can use Hex() for different conversions like hex to decimal, hex to binary, hex to string, and hex to octal. Here is an example:

Python3

# TypeConversion from decimal with base 10

# to hexadecimal form with base 16

# Taking input from user

# an integer with base 10

number = int(input("Enter a number with base 10\n"))

# The choices present to the user

print("a. Decimal to Hexadecimal ")

print("b. Decimal to Octal")

print("c. Decimal to Binary")

# taking user input

print("Enter your choice :- ")

choice = input()

# Running a variable choice

# Hexadecimal form if choice

# is set to 'a'

if choice is 'a':

# lstrip helps remove "0x" from the left

# rstrip helps remove "L" from the right,

# L represents a long number

print("Hexadecimal form of " + str(number) +

" is " + hex(number).lstrip("0x").rstrip("L"))

if choice is 'b':

# Octal representation is done

# by adding a prefix "0o"

print("Octal form of " + str(number) +

" is " + oct(number).lstrip("0o").rstrip("L"))

if choice is 'c':

# Binary representation is done by

# the addition of prefix "0b"

print("Binary form of " + str(number) +

" is "+bin(number).lstrip("0b").rstrip("L"))

Output

input variant a)

Enter a number with base 10
123
a. Decimal to Hexadecimal
b. Decimal to Octal
c. Decimal to Binary
Enter your choice:-
a
Hexadecimal form of 123 is 7b

input variant b)

Enter a number with base 10
123456789
a. Decimal to Hexadecimal
b. Decimal to Octal
c. Decimal to Binary
Enter your choice:-
a
Hexadecimal form of 123456789 is 75bcd15

Python Hex() Function Demonstrate TypeError

Python demonstrates TypeError when floating point values are passed as parameters.

Python3

# hex() accepts only integer values as parameters

print("The hexadecimal form of 11.1 is "

+ hex(11.1))

'''

# The hexadecimal conversion of floating

# point integers can be done using the

# function float.hex()

print("The hexadecimal form of 11.1 is "

+ float.hex(11.1))

# Output :

# The hexadecimal form of 11.1 is 0x1.6333333333333p+3

# Similarly, float.hex() throws a TypeError

# when integer values are passed in it.

'''

Output

Traceback (most recent call last):
File "/home/7e1ac7e34362fd690cdb72cf294502e1.py", line 2, in
print("The hexadecimal form of 11.1 is "+hex(11.1))
TypeError: 'float' object cannot be interpreted as an integer

Errors and Exceptions

Typeerror :  Returns Typeerror when anything other than 
integer type constants are passed as parameters.

Applications
Hex() is used in all the standard conversions. For example conversion of hexadecimal to decimal, hexadecimal to octal, and hexadecimal to binary.



retr0

hex() function in Python - GeeksforGeeks (2)

Improve

Previous Article

Python hash() method

Next Article

id() function in Python

Please Login to comment...

hex() function in Python - GeeksforGeeks (2024)
Top Articles
Infinite banking explained: Is this popular TikTok financial trend worth the hype? | Facet
Things to Do in Helmond in 2024 - Top Attractions, Local Food, Hotels & Travel Tips | Trip.com
The Tribes and Castes of the Central Provinces of India, Volume 3
Kem Minnick Playboy
Craigslist Niles Ohio
Chris wragge hi-res stock photography and images - Alamy
Caroline Cps.powerschool.com
Comcast Xfinity Outage in Kipton, Ohio
T&G Pallet Liquidation
Free Robux Without Downloading Apps
Wmlink/Sspr
Mercy MyPay (Online Pay Stubs) / mercy-mypay-online-pay-stubs.pdf / PDF4PRO
18443168434
Watch TV shows online - JustWatch
‘Accused: Guilty Or Innocent?’: A&E Delivering Up-Close Look At Lives Of Those Accused Of Brutal Crimes
Keniakoop
Summoners War Update Notes
2024 Non-Homestead Millage - Clarkston Community Schools
Craigslist Pets Sac
6001 Canadian Ct Orlando Fl
U/Apprenhensive_You8924
Drago Funeral Home & Cremation Services Obituaries
Https://Store-Kronos.kohls.com/Wfc
Amc Flight Schedule
Adam4Adam Discount Codes
Huntersville Town Billboards
Att.com/Myatt.
A Person That Creates Movie Basis Figgerits
Red8 Data Entry Job
F45 Training O'fallon Il Photos
Renfield Showtimes Near Paragon Theaters - Coral Square
Foodsmart Jonesboro Ar Weekly Ad
Harrison County Wv Arrests This Week
The Clapping Song Lyrics by Belle Stars
Darknet Opsec Bible 2022
Progressbook Newark
Mastering Serpentine Belt Replacement: A Step-by-Step Guide | The Motor Guy
Beaver Saddle Ark
Workday Latech Edu
Craigslist Greencastle
Pinellas Fire Active Calls
Columbia Ms Buy Sell Trade
WorldAccount | Data Protection
Express Employment Sign In
Danielle Ranslow Obituary
Cocaine Bear Showtimes Near Cinemark Hollywood Movies 20
LoL Lore: Die Story von Caitlyn, dem Sheriff von Piltover
فیلم گارد ساحلی زیرنویس فارسی بدون سانسور تاینی موویز
Swsnj Warehousing Inc
Theatervoorstellingen in Nieuwegein, het complete aanbod.
The Goshen News Obituary
Epower Raley's
Latest Posts
Article information

Author: Gregorio Kreiger

Last Updated:

Views: 6357

Rating: 4.7 / 5 (57 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Gregorio Kreiger

Birthday: 1994-12-18

Address: 89212 Tracey Ramp, Sunside, MT 08453-0951

Phone: +9014805370218

Job: Customer Designer

Hobby: Mountain biking, Orienteering, Hiking, Sewing, Backpacking, Mushroom hunting, Backpacking

Introduction: My name is Gregorio Kreiger, I am a tender, brainy, enthusiastic, combative, agreeable, gentle, gentle person who loves writing and wants to share my knowledge and understanding with you.