Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get nth byte of integer

Tags:

python

byte

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
like image 235
Juicy Avatar asked Sep 21 '15 12:09

Juicy


People also ask

How many bytes in an int?

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.

What is the hex value stored for for 2byte integer?

The hex should then be 29(base16) and 49(base16) respectively.

What is 0xff?

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.


3 Answers

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)
like image 200
Emil Vikström Avatar answered Nov 10 '22 02:11

Emil Vikström


def byte(number, i):
    return (number & (0xff << (i * 8))) >> (i * 8)
like image 29
grigoriytretyakov Avatar answered Nov 10 '22 03:11

grigoriytretyakov


>>> 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'
like image 20
luoluo Avatar answered Nov 10 '22 03:11

luoluo