简体   繁体   中英

Convert hexadecimal notation literally to string or vice versa

The function I'm writing gets a checksum (format: '*76') as a string (isolated from an NMEA string). This checksum in string format is called 'Obs' (Observed from string). It then computes the checksum from the rest of the string and gets that answer as hex (Terminal: 0x76), this will be called 'Com' (Computed from string). Now I need to convert one to the other to compare them agains each other.

I've tried stuff like:

HexObs = hex(Obs) #with Obs as '0x76' and '0*76'

Which gives me an error.

and

StrCom = str(Com)

Which gives: '118'

There were no previous questions in which I recognised my question. Does anyone know how to convert one to the other? Tnx in advance.

I think you're problem is getting the original into an actual hex form

tobs = '76'
obs = hex(int('0x' + tobs, 16))

that will give you an actual hex value to compare

alternately you could use:

tobs = '76'
com = '0x76'
tcom = com[2:]

then compare tobs & tcom

To go from a string hex representation, use:

>>> int('0x76', 16)
118

The second argument is the base.

To go from an integer to a string hex representation, use:

>>> hex(118)
'0x76'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM