I have the following integer:
target = 0xd386d209
print hex(target)
How can I print the nth byte of this integer? For example, expected output for the first byte would be:
0x09
The int and unsigned int types have a size of four bytes. However, portable code should not depend on the size of int because the language standard allows this to be implementation-specific.
The hex should then be 29(base16) and 49(base16) respectively.
Overview. 0xff is a number represented in the hexadecimal numeral system (base 16). It's composed of two F numbers in hex. As we know, F in hex is equivalent to 1111 in the binary numeral system. So, 0xff in binary is 11111111.
You can do this with the help of bit manipulation. Create a bit mask for an entire byte, then bitshift that mask the number of bytes you'd like. Mask out the byte using binary AND and finally bitshift back the result to the first position:
target = 0xd386d209
bit_index = 0
mask = 0xFF << (8 * bit_index)
print hex((target & mask) >> (8 * bit_index))
You can simplify it a little bit by shifting the input number first. Then you don't need to bitshift the mask
value at all:
target = 0xd386d209
bit_index = 0
mask = 0xFF
print hex((target >> (8 * bit_index)) & mask)
def byte(number, i):
return (number & (0xff << (i * 8))) >> (i * 8)
>>> def print_n_byte(target, n):
... return hex((target&(0xFF<<(8*n)))>>(8*n))
...
>>> print_n_byte(0xd386d209, 0)
'0x9L'
>>> print_n_byte(0xd386d209, 1)
'0xd2L'
>>> print_n_byte(0xd386d209, 2)
'0x86L'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With