[Tutor] conversion confusion
Lloyd Kvam
pythontutor at venix.com
Wed Oct 1 12:19:30 EDT 2003
int(value2add,16) requires that value2add be a string with characters
from the set: 0123456789abcdefABCDEF
It won't work with any old string, such as 'm'.
The CRC equation doesn't work with strings, it works with integers. To turn
a single character into its integer representation, python provides the ord
function.
CRCval = ord('m') ^ int(seed,16)
You shouldn't need any hex values within your processing. Having said that,
to turn the hex string '6d' into an integer, you'd use the int function:
int('6d',16) which equals 109
ord('m') also equals 109
If you want to post the problem code, we can probably help. I'd expect your
code should look something like:
input_char = serial.get_a_character() # I made up the function name
CRCval = ord(input_char) ^ int(seed,16)
print "input_char(hex): %x CRC(hex): %x" % (input_char, CRCval)
One other point. Your device documentation may show stuff in terms of
C programming code. In C, 'm' is actually an integer not a string. So
a C programmer can write:
'n' - 'm'
and get a result of 1. In python, we'd write:
ord('n') - ord('m')
and also get 1.
Hope this helps. Try giving us a code snippet if necessary.
Stanfield, Vicki {D167~Indianapolis} wrote:
> Well, I still can't get this to work right. It works fine when the value2add is a small number, but when it is an 'm' or some other letter, it doesn't work. If I fake it out and send the 'm' as a string representation of its hex value ('6d'), it will work. So the problem must be that after I hexlify the 'm', it is numeric rather than a string which is what the equation which follows wants.
>
> CRCval=int(value2add,16) ^ int(seed,16)
>
> How does one turn a hex number 6d into a string so that the equation will happily take it? I may be going about things strangely, but the value comes in as an 'm' and needs to be a string '6d'. How do I get from one to the other?
>
> --vicki
>
> P.S. I apologize if I am being dense here; some parts of this come easy and some with great difficulty.
>
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-443-6155
fax: 801-459-9582
More information about the Tutor
mailing list