Convert 4 byte unsigned ints to 0-127

Issue

I need to convert a range of values I receive from another software.

They come in the from of 4 byte integers (0 – 0xFFFFFFFF) but I want to display them as a range of 0-127.

I’m not familiar with how unsigned ints work. When I tried setting the value to 127 from inside the software I get a reading of "-16" value in my application.

Could you please give me an explanation of how this works or give me some relevant resources to study?

I’d prefer language agnostic answers but I happen to use Javascript.

Solution

Firstly, a 4 byte integer can contain values spanning a range of over 4 billion. It is not clear as to how you intend to represent these with a range of 0-127. If the values coming from the other program can be guaranteed to always be in the range 0-127 then that of course, won’t be an issue. However you will need to consider what happens when larger values (or negative values) are received.

Secondly, an integer can be signed or unsigned. An 8 bit variable (one byte) can have the signed range -128 through 127 or the unsigned range 0 through 255. (This may represent actual numbers, or maybe an ASCII character or a bit-field or any other number of things. You must know ahead of time what the value represents and if it is signed or unsigned.)

Let’s assume it simply represents a number. If it is a signed number then the most significant bit will be set for negative numbers and cleared for positive numbers. For unsigned integers, the most significant bit is just the same as any other bit.

Staying with the 8-bit byte, a value of 0b10000001 would be:
unsigned: 129
signed: -127
A value of 0b00000001 will always be 1 whether the value is signed or unsigned. There will be plenty of tutorials on the internet that discuss this subject.

Thirdly, you will need to know if the 4 bytes you are receiving are "little-endian" or "big-endian". In other words, when you get the first byte, is this the most significant byte or the least significant byte? If you get this around the wrong way then the resulting number will be meaningless.

Before any meaningful answer can be given you will need to provide much more information. Nonetheless, I hope I have been able to point you in the right direction.

Answered By – mait

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.