Juicy
Juicy

Reputation: 12530

Get nth byte of integer

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

Upvotes: 9

Views: 13582

Answers (4)

Emil Vikström
Emil Vikström

Reputation: 91983

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
byte_index = 0
mask = 0xFF << (8 * byte_index)
print hex((target & mask) >> (8 * byte_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
byte_index = 0
mask = 0xFF
print hex((target >> (8 * byte_index)) & mask)

Upvotes: 13

luoluo
luoluo

Reputation: 5533

>>> 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'

Upvotes: 1

grigoriytretyakov
grigoriytretyakov

Reputation: 177

def byte(number, i):
    return (number & (0xff << (i * 8))) >> (i * 8)

Upvotes: 3

metatoaster
metatoaster

Reputation: 18978

This only involves some simple binary operation.

>>> target = 0xd386d209
>>> b = 1
>>> hex((target & (0xff << b * 8)) >> b * 8)
'0x9'
>>> hex((target & (0xff << b * 8)) >> b * 8)
'0xd2'

Upvotes: 0

Related Questions