[Tutor] ASCII hex to binary

Zak Arntson zak@harlekin-maus.com
Mon Aug 4 16:32:01 EDT 2003


> Jimmy,
<various cuts below>
> If its just the total grab each value convert it into its decimal
> equivalent
> and add them together. Then just convert it to binary.
>
> If separate values are needed I would put each position into a
> dictionary probably with a decimal value.
>
> Then write a function that converts each to a binary value putting it back
> in the dictionary.
>
> Alan

>> Hello *
>>
>> Can some please tell me how can i express an ASCII hexadecimal string in
>> the binary form with python.
<SNIP!>
>> Thanks in advance.

You can also take advantage of the fact that a single hex value (0-F) can
be represented as a 4-digit binary number. Here's a highly obfuscated
version, which I wouldn't recommend including anywhere.

hex_to_bin = lambda s: ''.join(map(lambda c: [''.join(['01'[2**j & k > 0]
for k in range(16) for j in range(3, -1, -1)][i:i+4]) for i in range(0,
256, 4)][int(c, 16)], s))

I have this feeling that I can simplify it a bit by avoiding two joins,
but I've already put too much wasted effort into it. It's also not very
efficient, with lambda being used over and over again.

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em




More information about the Tutor mailing list