# decimal to binary

Manish Jethani manish.j at gmx.net
Fri Jul 25 22:43:33 CEST 2003

```manuel wrote:

> This is the first time that I try to handle
> binary file.
>
> I read a tga file, and store all bytes in a list:
>
> ---------------------------------------
> #LETTURA DEL FILE TGA
>  listByte = []
>  try:
>   f = open(filename,'rb')
>  except IOError,(errno,strerror):
>   msgstring = "I/O error(%s): %s" % (errno, strerror); Draw()
>   return
>  msgstring = "Parsing tga..."; Draw()
>  f.close()
> ------------------------------------------
>
> I use ord() to convert the value of byte in
> integer, if I don't make this, I've the ASCII
> symbol...

You CAN store the byte as it is, in a string.  So, for example,
you can store
'a(*@'
[97, 40, 42, 64]
But it depends on your requirements.

> 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.

This function returns the binary representation as a string:

def foo(i):
b = ''
while i > 0:
j = i & 1
b = str(j) + b
i >>= 1
return b

bin = foo(listByte[17])
bin[-4]  # 4th (3rd) bit
bin[-5]  # 5th (4th) bit

You have to check for IndexError, or check the length of the string.

BUT!  But you don't need to do this in order to get the value of
the 4th (3rd) bit.  Just do this:

if listByte[17] & (1 << 3):
<bit is set>
else:
<bit is not set>

For the 5th (4th) bit, change '<< 3' to '<< 4'; and so on.

-Manish

--
Manish Jethani (manish.j at gmx.net)
phone (work) +91-80-51073488

```