Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two's complement conversion

I need to convert bytes in two's complement format to positive integer bytes. The range -128 to 127 mapped to 0 to 255.

Examples: -128 (10000000) -> 0 , 127 (01111111) -> 255, etc.

EDIT To clear up the confusion, the input byte is (of course) an unsigned integer in the range 0 to 255. BUT it represents a signed integer in the range -128 to 127 using two's complement format. For example, the input byte value of 128 (binary 10000000) actually represents -128.

EXTRA EDIT Alrighty, lets say we have the following byte stream 0,255,254,1,127. In two's complement format this represents 0, -1, -2, 1, 127. This I need clamping to the 0 to 255 range. For more info check out this hard to find article: Two's complement

like image 571
Yehonatan Avatar asked Sep 28 '10 12:09

Yehonatan


People also ask

How do you convert to two's complement?

To get 2's complement of binary number is 1's complement of given number plus 1 to the least significant bit (LSB). For example 2's complement of binary number 10010 is (01101) + 1 = 01110.

What is the 2's complement of 5?

If you take the 2's complement of 5 ( 0101 ), you get 1011 which is how you represent -5 . If you take the 2's complement of -5 ( 1011 ), you get 0101 , which is 5 .


2 Answers

From you sample input you simply want:

sbyte something = -128;

byte foo = (byte)( something + 128);
like image 51
leppie Avatar answered Sep 24 '22 05:09

leppie


new = old + 128;

bingo :-)

like image 44
BarsMonster Avatar answered Sep 25 '22 05:09

BarsMonster