Python Built‑in Functions: hex(), oct(), bin(), chr() and ord()
This article explains the purpose, syntax, parameters, return values and typical usage examples of Python’s built‑in conversion functions hex(), oct(), bin(), chr() and ord(), including edge cases and custom class implementations.
1. hex() function
The hex() built‑in converts a decimal integer to its hexadecimal representation and returns it as a string.
hex(255)
# '0xff'
hex(-42)
# '-0x2a'
hex(1L)
# '0x1L'
hex(12)
# '0xc'
type(hex(12))
#Floating‑point numbers cannot be converted with hex() ; use float.hex() instead.
float.hex(10.1)
# 0x1.4333333333333p+32. oct() function
The oct() built‑in converts an integer to an octal string. Passing a float or a string raises TypeError .
a = oct(10)
print(a)
# '0o12'
print(type(a))
#
# Passing a float
oct(10.0)
# TypeError: 'float' object cannot be interpreted as an integer
# Passing a string
oct('10')
# TypeError: 'str' object cannot be interpreted as an integerIf the argument is not an integer, it must be an object that defines __index__() returning an integer.
# Example without __index__ – fails
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
a = Student('Kim', 10)
oct(a) # TypeError
# __index__ returns non‑int – fails
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __index__(self):
return self.name # returns str
# __index__ returns int – succeeds
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __index__(self):
return self.age
a = Student('Kim', 10)
print(oct(a))
# '0o12'3. bin() function
The bin() built‑in returns the binary representation of an integer as a string.
a = bin(1)
print(a)
# '0b1'
print(type(a))
#If the argument is not an integer, the object must implement __index__() that returns an integer.
# Object without __index__ – fails
class A: pass
bin(A()) # TypeError
# __index__ returns non‑int – fails
class A:
def __index__(self):
return "1"
bin(A()) # TypeError
# __index__ returns int – succeeds
class A:
def __index__(self):
return 1
c = A()
print(bin(c))
# '0b1'4. chr() function
chr() takes an integer (0‑255 in Python 2, Unicode code point in Python 3) and returns the corresponding character.
beg = int(input("Enter start value: "))
end = int(input("Enter end value: "))
print("Dec\tHex\tChar")
for i in range(beg, end+1):
print("{}\t{}\t{}".format(i, hex(i), chr(i)))5. ord() function
ord() is the inverse of chr() ; it takes a one‑character string and returns its Unicode code point as an integer.
print('ord(a)', ord('a')) # 97
print('ord(\u2020)', ord('\u2020')) # 8224
print('ord(1)', ord('1')) # 49These built‑in functions are essential for numeric‑base conversions and character encoding/decoding in Python.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.