binary numbers

Max M maxm at mxm.dk
Tue Oct 5 18:52:06 EDT 2004


Larry Bates wrote:
> Brad Tilley wrote:
> 
>> How can I specify that a number be represented in binary format when 
>> passing it to a function? I'm working with the Windows registry and 
>> REG_BINARY values expect numbers in binary form...
>>
>> This would be nice:
>>
>> import binary
>> x = binary(5)


I am not quite shure that I understand you correctly. But I think so.

You are probaly loking for the struct module. It handles strings as 
lumps of binary data. So if you want to store something as "binary" you 
convert it to a string containing binary data, and pass that string to 
the registry.

It's not that hard. A function doing what you describe above could be 
written a bit like:

# converts int to "binary short"
from struct import pack
x = pack('h', 5)

So technically x is now a string, but it contains the binary 
representation of bytes that is a "short" on your system. I am not shure 
if the registry expects a short though.


more info in the docs at:

4.3 struct -- Interpret strings as packed binary data



-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science



More information about the Python-list mailing list