Skip to content

Instantly share code, notes, and snippets.

@astraw38
Created May 12, 2015 13:42
Show Gist options
  • Save astraw38/d8185cc6127114a642c4 to your computer and use it in GitHub Desktop.
Save astraw38/d8185cc6127114a642c4 to your computer and use it in GitHub Desktop.
to_byte_array
from ctypes import *
def to_byte_array(val):
width = val.bit_length()
width += 8 - ((width % 8) or 8)
fmt = "{:0%sb}" % width
str_val = fmt.format(val)
n = 8
print "Str_val: \t{}".format(str_val)
return [str_val[i:i+n] for i in range(0, len(str_val), n)]
large_numbers = [65537, 12345678900987654321, 1233, 1, 6553455]
hulk_number = 500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
large_numbers.append(hulk_number)
for num in large_numbers:
print "Dec: \t{}\n"\
"Bin: \t{:b}".format(num, num)
byarray = to_byte_array(num)
print "Converted: \t{}".format(byarray)
build_array = c_ubyte * len(byarray)
final_array = build_array(*[int(x, 2) for x in byarray])
print "Byte Array:\t{}".format(final_array)
print " Raw: \t{}".format([x for x in final_array])
print " Bin: \t{}".format(["{:0b}".format(x) for x in final_array])
print ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment