'How do I correctly pass uint32 to a Protobuf object in Python?

For quite a long time I can not find a solution to this problem on the Internet. I must say that it is impossible to change the data type for a specific field, since the product has already been released and there is no way to replace the decoding of the Protobuf message or completely abandon Protobuf :(

The problem is that the Protobuf data type, number 5, accepts only the standard Python int, which may be too large due to the fact that it is not an unsigned int.

I tried using numpy. uint32 and ctypes. c_uint32, but both options end up being converted automatically to regular Python int and I get the error: "ValueError: Value out of range: 2902080034". I need to somehow fit in the 5th Protobuf data type the first 32 bits of UUID4 as a number.

I hope for help, thank you in advance. Unfortunately, in my opinion, this may be a popular problem not described here before.



Solution 1:[1]

Type .proto uint32 corresponds to python int, i.e. it has range -2147483648 through 2147483647.

One solution is to convert your unsigned 32 bit value to a signed one by:

if (value & 0x80000000):
    value = -0x10000000 + value

The conversion is as suggested here:
How to get the signed integer value of a long in python?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thekyria