Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a python equivalent of the octave command `format bit`?

Tags:

python

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

like image 845
A.Apte Avatar asked Jul 21 '15 16:07

A.Apte


Video Answer


1 Answers

TL;DR; No, there is not Python equivalent

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.

like image 64
Hannes Karppila Avatar answered Nov 15 '22 00:11

Hannes Karppila