Result not expected in hex logical "and" with python

1

the next is part of a program I'm doing, I need to do an "AND" operation between 2 hexadecimal numbers, in the first part all is ok, but in the second part when I use an Hex number too long the result is different than I expected:

#this is ok
x = hex(268435456)       
transition = int(x, 16) & 0x000000FF 
>>>> print transition
>>>> 6

#this does not work
y = hex(268435456)
transition = int(y,16) & 0xFFFFFF00
>>>> print transition
>>>> 268435456
#in this case the result should be 10 00 00 00

Do you know what is happening?

python
hex
long-integer
asked on Stack Overflow Nov 9, 2017 by Oscoke

2 Answers

1

Your result is 10 00 00 00, you were just printing the decimal representation instead of the hexadecimal representation.

>>> print '{:x}'.format(268435456)
10000000
answered on Stack Overflow Nov 9, 2017 by wim • edited Nov 9, 2017 by wim
1

The result is 0x10000000 hex, which is 268435456 in decimal. See hex(268435456).

You don't need to convert your decimal numbers to strings and parse them back to ints. Just do:

x = 268435456
y = x
transition_x = x & 0xFF
transition_y = y & 0xFFFFFF00
print transition_x # 0
print transition_y # 268435456

Your first result is wrong. The result is 0, not 6.

If you define an integer number using decimal notation (1234), hexadecimal notation (0x4d2) or octal notation (0o2322 or 02322[py2]), it will always be stored as an int internally. The number literals I used above all represent the same decimal value of 1234. Printing the number will always use decimal notation, unless you convert it explicitly to a certain string representation.

answered on Stack Overflow Nov 9, 2017 by Jan Christoph Terasa • edited Nov 9, 2017 by Jan Christoph Terasa

User contributions licensed under CC BY-SA 3.0