views:

119

answers:

5

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

+3  A: 

From you sample input you simply want:

sbyte something = -128;

byte foo = (byte)( something + 128);
leppie
Please see my edits. Hope its clearer now.
Yehonatan
@Yehonatan: But how do you want to represent -1 in the 0 to 255 range?
leppie
+1  A: 

You could be describing something as simple as adding a bias to your number ( in this case, adding 128 to the signed number ).

Alex Reece
If only it was that simple.
Yehonatan
+5  A: 
new = old + 128;

bingo :-)

BarsMonster
@Bars, since I couldn't find the `bingo` keyword, I've edited your answer for readability :-)
paxdiablo
Is 'old' the original byte value or the conversion of it? If its the original byte value then this gives the wrong answer. If its the latter then that is the process is what I'm asking for.
Yehonatan
A: 

If I undestood correctly, your problem is how to convert the input, which is really a signed-byte (sbyte), but that input is stored in a unsigned integer, and then also avoid negative values by converting them to zero.

To be clear, when you use a signed type (like ubyte) the framework is using Two's complement behind the scene, so just by casting to the right type you will be using two's complement.

Then, once you have that conversion done, you could clamp the negative values with a simple if or a conditional ternary operator (?:).

The functions presented below will return 0 for values from 128 to 255 (or from -128 to -1), and the same value for values from 0 to 127.

So, if you must use unsigned integers as input and output you could use something like this:

private static uint ConvertSByteToByte(uint input)
{
    sbyte properDataType = (sbyte)input; //128..255 will be taken as -128..-1
    if (properDataType < 0) { return 0; } //when negative just return 0
    if (input > 255) { return 0; } //just in case as uint can be greater than 255
    return input;
}

Or, IMHO, you could change your input and outputs to the data types best suited to your input and output (sbyte and byte):

private static byte ConvertSByteToByte(sbyte input)
{
    return input < 0 ? (byte)0 : (byte)input;
}
Protron
A: 

Try

sbyte signed = (sbyte)input;

or

int signed = input | 0xFFFFFF00;
Bart van Heukelom