On Mon, Feb 17, 2020 at 3:40 AM Mark Dickinson <mdickin...@enthought.com> wrote:
>
> ananthakrishnan15.2001ï¼ gmail.com wrote:
> > binary.twos_complement(0b0011)==1101
> > binary.twos_complement(0b00000011)==11111101
>
> How would you make that possible, when `0b0011` and `0b00000011` are the 
> exact same integer?

Easy: you simply have 0b1101 and 0b11111101 actually be display
phenomena. Both of them represent -3 in a particular field size.
Unfortunately the built-in bin() function doesn't take a width
argument, but you can easily create that:

def binary(n, width=None):
    if width: return format(n & (1<<width) - 1, "0%db" % width)
    return format(n, "b")

Now you can ask for any number's binary representation in a field of N
bits, negative numbers included.

With that added, you can now use Python's ordinary integers. In fact...

import sys
sys.displayhook = lambda val: print(binary(val, 8)) if type(val) is
int else print(val)

Tada! Now your REPL works with eight-bit binary values.

ChrisA
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/DC6BLSPC6TCM6MLHOGSZ44MRD6PAFECF/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to