Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python and overflowing byte?

I need to make a variable with similar behaviour like in C lanquage. I need byte or unsigned char with range 0-255. This variable should overflow, that means...

myVar = 255
myVar += 1

print myVar #!!myVar = 0!!
like image 899
Meloun Avatar asked Jun 05 '10 11:06

Meloun


People also ask

What is overflow in Python?

In Python, OverflowError occurs when any operations like arithmetic operations or any other variable storing any value above its limit then there occurs an overflow of values that will exceed it's specified or already defined limit. In general, in all programming languages, this overflow error means the same.

How do you pass bytes in Python?

When an integer value is passed to the bytes() method, it creates an array of that size (size = integer value) and initializes the elements with null bytes. In the following example, we are passing the value 6 to the bytes() method so the function created an array of size 6 and initialized the elements with null bytes.

What does bytes () in Python do?

Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.

What is the difference between bytes and Bytearray in Python?

The primary difference is that a bytes object is immutable, meaning that once created, you cannot modify its elements. By contrast, a bytearray object allows you to modify its elements. Both bytes and bytearay provide functions to encode and decode strings.


1 Answers

I see lots of good answers here. However, if you want to create your own type as you mentioned, you could look at the Python Data model documentation. It explains how to make classes that have customized behaviours, for example emulating numeric types.

With this info, you could make a class like so:

class Num:
    def __init__(self, n):
        self.n = (n % 256)

    def __repr__(self):
        return repr(self.n)

     def __add__(self, other):
        return Num(self.n+int(other))

    # transform ourselves into an int, so
    # int-expecting methods can use us
    def __int__(self):
        return self.n

Then you can do things like this:

>>> a = Num(100)
>>> print a
100
>>> b = a + 50
>>> print b
150
>>> c = Num(200)
>>> d = a + c
>>> print d
44

I realize that you may want to support more operations than I've shown in Num, but from this example and the documentation, it should be fairly clear how to add them.

like image 102
Blair Conrad Avatar answered Sep 30 '22 07:09

Blair Conrad