hm. Alguns programadores necessitam ver os bits das variáveis. em alguns casos, mostrar os bits pode ser interessante e extremamente útil – quando está escrevendo algum driver, ou calculando endereços de rede e broadcast.
Segue um exemplo em python que oferece esse recurso:
$ python bitprint.py A = 01000001 B = 01000010 C = 01000011 D = 01000100 E = 01000101 F = 01000110 G = 01000111 H = 01001000 I = 01001001 J = 01001010 K = 01001011 L = 01001100 M = 01001101 N = 01001110 O = 01001111 P = 01010000 Q = 01010001 R = 01010010 S = 01010011 T = 01010100 U = 01010101 V = 01010110 W = 01010111 X = 01011000 Y = 01011001 Z = 01011010 192.168.19.5 = 11000000.10101000.00010011.00000101
Segue o código do programa, ou módulo:
#!/usr/bin/env python
# coding: utf-8
# bitprint.py 20081703 AF
import sys, ctypes
class Bits:
"""
Imprime os bits de uma determinada variável, compatível apenas com os
tipos básicos da linguagem C - int, uint8, uint16, long, double, etc.
Os tipos disponíveis estão no módulo ctypes do python.
Para mais informações veja XBits.
"""
allowed = [getattr(ctypes, k) for k in dir(ctypes) if k.startswith('c_')]
def __init__(self, src):
self._bitseq(src)
def _bitseq(self, src):
tb = type(src)
if tb not in self.allowed:
raise TypeError('Tipo não permitido: %s' % tb)
size = ctypes.sizeof(src)*8
mask = 1<<size-1
buff = ''
for n in range(size):
buff += (src.value & mask) and '1' or '0'
mask >>= 1
self.bits = buff
def __str__(self):
return self.bits
def __len__(self):
return len(self.bits)
class XBits(Bits):
"""
Imprime os bits de uma variável do python, sendo do tipo:
str, int, list ou tuple
Exemplos:
print XBits('A')
print XBits(200)
print XBits(('A', 'B'), delim=', ')
print XBits([192, 168, 19, 5], format=ctypes.c_uint8, delim='.')
"""
def __init__(self, src, format=ctypes.c_int, delim=''):
if type(src) is str:
buff = []
for n in src:
self._bitseq(ctypes.c_uint8(ord(n)))
buff.append(self.bits)
self.bits = delim.join(buff)
elif type(src) in [list, tuple]:
buff = []
for n in src:
buff.append(str(XBits(n, format, delim)))
self.bits = delim.join(buff)
else:
Bits.__init__(self, format(src))
if __name__ == '__main__':
print '\n'.join(['%s = %s' % (chr(n), str(XBits(chr(n)))) for n in range(ord('A'), ord('Z')+1)])
print '192.168.19.5 = %s' % XBits([192, 168, 19, 5], format=ctypes.c_uint8, delim='.')

Comentários