decimal to binary

Christopher Koppler klapotec at chello.at
Fri Jul 25 17:11:33 EDT 2003


On Fri, 25 Jul 2003 18:52:00 GMT, "manuel"
<manuelbastioniNOSPAM at tin.it> wrote:

>I use ord() to convert the value of byte in
>integer, if I don't make this, I've the ASCII
>symbol...
>
>But, for listByte[17], I must read the sequence
>of 0 and 1, because I must know the 4° and 5° bit:
>this bits specify the image origin.
>
>How I can read the 4° and 5° bit from listByte[17]?


You can use this function to generate a list of digits (least
significant first!) from any integer, with the default being the 8
binary digits of one byte (and no checking for anything):

def digitlist(value, numdigits=8, base=2):
	val = value
	digits = [0 for i in range(numdigits)]
	for i in range(numdigits):
		val, digits[i] = divmod(val, base)
	return digits

>>> digitlist(234) # binary 11101010
[0, 1, 0, 1, 0, 1, 1, 1]
>>> digitlist(39)  # binary 00100111
[1, 1, 1, 0, 0, 1, 0, 0]

Now you can easily access the 4th and 5th elements (which are probably
reversed if you needed the 4th and 5th bit most significant first)...

Hope this helps,
Christopher

--
Christopher




More information about the Python-list mailing list