Mirror imaging binary numbers

mensanator at aol.com mensanator at aol.com
Wed Dec 6 18:42:25 EST 2006


Craig wrote:
> Matimus wrote:
>
> > Craig wrote:
> > > I'm trying to switch binary numbers around so that the MSB becomes the
> > > LSB etc.
> >
> > What do you mean 'binary numbers'? They are all binary. If you mean the
> > int type, they are 32 bits long and there are 16 bits between the MSB
> > and LSB (Most/Least Significant _Byte_). Do you want to swap the most
> > significant word with the least significant word? Swap the most
> > significant nibble with the least significant nibble in a Byte? Or do
> > you want to completely reverse the bit order?
> >
> > To swap nibbles in a byte:
> >
> > reverseVal = (val & 0xf) << 4  |  (val & 0xf0) >> 4
> >
> > Basicly you are going to need to use the bit operators (|,&, << and >>)
> > to get what you need. If you could be more specific perhaps I could be
> > of more help.
>
> Thanks so much for the response.  I have an array of individual bytes
> which will eventually make up a binary bitmap image that is loaded onto
> an LCD screen (1 = black dot, 0 = white dot).  At the moment each byte
> is reversed to what it should be (completely reverse the bit order):
> e.g 00111101 should be 10111100, 11001100 should be 00110011, etc.  It
> is not an int problem as such, it is more a bit level swap if you get
> what I mean.  If you could help that would be great.

>>> import gmpy                   # GNU Multi-precision library for Python
>>> for i in xrange(16):
	s = gmpy.digits(i,2)      # turn int to a base 2 string
	p = '0'*(8-len(s)) + s    # pad out leading 0's
	r = ''.join(reversed(p))  # reverse it
	print p,r                 # voila


00000000 00000000
00000001 10000000
00000010 01000000
00000011 11000000
00000100 00100000
00000101 10100000
00000110 01100000
00000111 11100000
00001000 00010000
00001001 10010000
00001010 01010000
00001011 11010000
00001100 00110000
00001101 10110000
00001110 01110000
00001111 11110000




More information about the Python-list mailing list