Python - Decimal to Hex, Reverse byte order, Hex t

2020-06-06 05:33发布

I've been reading up a lot on stuct.pack and hex and the like.

I am trying to convert a decimal to hexidecimal with 2-bytes. Reverse the hex bit order, then convert it back into decimal.

I'm trying to follow these steps...in python

Convert the decimal value **36895** to the equivalent 2-byte hexadecimal value:

**0x901F**
Reverse the order of the 2 hexadecimal bytes:

**0x1F90**
Convert the resulting 2-byte hexadecimal value to its decimal equivalent:

**8080**

5条回答
放我归山
2楼-- · 2020-06-06 05:56
>>> x = 36895
>>> ((x << 8) | (x >> 8)) & 0xFFFF
8080
>>> hex(x)
'0x901f'
>>> struct.unpack('<H',struct.pack('>H',x))[0]
8080
>>> hex(8080)
'0x1f90'
查看更多
相关推荐>>
3楼-- · 2020-06-06 06:03

Keep in mind that 'hex'(base 16 0-9 and a-f) and 'decimal'(0-9) are just constructs for humans to represent numbers. It's all bits to the machine.

The python hex(int) function produces a hex 'string' . If you want to convert it back to decimal:

>>> x = 36895
>>> s = hex(x)
>>> s
'0x901f'
>>> int(s, 16)  # interpret s as a base-16 number
查看更多
仙女界的扛把子
4楼-- · 2020-06-06 06:04

Print formatting also works with strings.

# Get the hex digits, without the leading '0x'
hex_str = '%04X' % (36895)

# Reverse the bytes using string slices.
# hex_str[2:4] is, oddly, characters 2 to 3.
# hex_str[0:2] is characters 0 to 1.
str_to_convert = hex_str[2:4] + hex_str[0:2]

# Read back the number in base 16 (hex)
reversed = int(str_to_convert, 16)

print(reversed) # 8080!
查看更多
你好瞎i
5楼-- · 2020-06-06 06:10

To convert from decimal to hex, use:

dec = 255
print hex(dec)[2:-1]

That will output the hex value for 255. To convert back to decimal, use

hex = 1F90
print int(hex, 16)

That would output the decimal value for 1F90.

You should be able to reverse the bytes using:

hex = "901F"
hexbyte1 = hex[0] + hex[1]
hexbyte2 = hex[2] + hex[3]
newhex = hexbyte2 + hexbyte1
print newhex

and this would output 1F90. Hope this helps!

查看更多
▲ chillily
6楼-- · 2020-06-06 06:19

My approach


import binascii

n = 36895
reversed_hex = format(n, 'x').decode('hex')[::-1]
h = binascii.hexlify(reversed_hex)
print int(h, 16)

or one line

print int(hex(36895)[2:].decode('hex')[::-1].encode('hex'), 16)
print int(format(36895, 'x').decode('hex')[::-1].encode('hex'), 16)
print int(binascii.hexlify(format(36895, 'x').decode('hex')[::-1]), 16)

or with bytearray

import binascii

n = 36895
b = bytearray.fromhex(format(n, 'x'))
b.reverse()
print int(binascii.hexlify(b), 16)
查看更多
登录 后发表回答