Two's complement conversion

Yehonatan picture Yehonatan · Sep 28, 2010 · Viewed 33k times · Source

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

Answer

leppie picture leppie · Sep 28, 2010

From you sample input you simply want:

sbyte something = -128;

byte foo = (byte)( something + 128);