hex to bin 16 bit word

P

python

Is there an other way to do this?

What to decode hex '0xC0A8' and return signed short int.
(-16216,)


Above works just wondering if there is cleaner way without writing a
function.

Bill
 
S

Steven D'Aprano

Is this right?

n = int('0xC0A8', 16)
if n >= 0xffff:
n -= 0x10000

No.
.... n -= 0x10000
....49320


Should be -16216.

Personally, I don't see why the OP doesn't just use struct.unpack to
unpack a struct.
 
G

Grant Edwards

Is this right?

n = int('0xC0A8', 16)
if n >= 0xffff:
n -= 0x10000

Yes, as long as the input value doesn't exceed 0x1ffff. This is
probably better:

n = int('0xc0a8'16) & 0xffff
 
P

Paul Rubin

Steven D'Aprano said:

Oops, I meant n >= 0x7fff. Checking the sign bit.

Grant Edwards said:
Yes, as long as the input value doesn't exceed 0x1ffff. This is
probably better:

n = int('0xc0a8'16) & 0xffff

Yeah, I was relying on the specification that the input was 16 bits.
 
G

Grant Edwards

Yes, as long as the input value doesn't exceed 0x1ffff. This is
probably better:

n = int('0xc0a8'16) & 0xffff

Oops, missed the "signed" part of the requirement.

n = int('0xc0a8',16) & 0xffff

if (n & 0x8000): n |= -1 & ~0xffff
 
G

Grant Edwards

Oops, missed the "signed" part of the requirement.

n = int('0xc0a8',16) & 0xffff

if (n & 0x8000): n |= -1 & ~0xffff

or this:

if (n & 0x8000): n = -((~n & 0x7fff) + 1)
 
P

python

snip

Thanks for all you suggestions.

This was sent via email. Original solution with struct was not
to bad but less clear that this was sent to me via email.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
EmeliaBryc

Latest Threads

Top