In octave, all the numerical output subsequent to the command format bit
will show the native bit representation of numbers as stored in the memory. For example,
octave:1> format bit
octave:2> 0.5
ans = 0011111111100000000000000000000000000000000000000000000000000000
octave:7> 2
ans = 0100000000000000000000000000000000000000000000000000000000000000
octave:3> format
octave:4> 0.5
ans = 0.50000
Is there an equivalent command in python to show all the numbers in their native-bit representation (so the output is as shown below)?
>>> "equivalent of the octave format bit command"
>>> 0.5
0011111111100000000000000000000000000000000000000000000000000000
(This is very different from the binary representation for 0.5.)
You are not supposed to need this information when you are using Python. Setting "output mode" like you did using octave is just not possible (without modifying Python itself). If you really want all outputs in other format than default, you could write custom function for that, and maybe even override default print
function if you are using Python 3.
If you just want to see binary representation of number, you can use bin(number)
function for integers. For floats you can use float.hex(number)
.
If we really want to see internal reprensentation, it requires some work, little bit of black magic and ctypes
library. It is not easy (or anyhow usable) to get this data when using Python, but I created function that shows us how float is internally represented:
We know that floats in Python floats are IEEE 754 double precision floating point numbers, so they use 8 bytes (64 bits) of memory.
import ctypes
def show_float(x):
asdouble = ctypes.c_double(x)
xpointer = ctypes.addressof(asdouble)
xdata = ctypes.string_at(xpointer, 8)
print "".join([bin(ord(i))[2:] for i in xdata])
x = 3.14
show_float(x) # prints 1111110000101111010111010001101110001111010011000000
Integers are harder, because representation is not same in all implementations. You can find one example here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With