# Help : Converting 8 bit to 16 bit

Status
Not open for further replies.

#### Maverickmax

##### Advanced Member level 1
signed 8 bits

Hi

I am struggling to understand why negative 8 bit convert to 16 bit ? What about positive?

What is the benefit?

Code:
if (data[i]&0x0080)
data[i] += 0xFF00; // convert to negative 16-bit
else
data[i] = data[i];
end

#### trekkytekky

##### Member level 5
The most significant bit of a signed number is the minus bit. Without the adjustment to a 16 bit ('+= 0xFF00') negative an 8 bit negative would be still be a positive number in signed 16 bit.

Because we only want to convert a range limited subset, we need to adjust the negative value.

In a signed 8 bit number we go from -128 (0x80) through -1 (0xFF) then 0 to +127 (0x7F).

In a signed 16 bit we go from -32768 (0x8000) through -128 (0xFF80) to -1 (0xFFFF) then 0 through +127 (0x007F) to 32767 (0x7FFF).

As you can see, the positive side need no adjustment, but the negative needs to be within -128 from zero (0xFF80) for the conversion to work.

Try googling 'twos complement' if you need more information on how this works

#### arthur0

##### Full Member level 2
I can’t remember a situation where I needed to do this ”conversion” (called sign extension) myself! Why would you?
Use casting [with care] instead and the compiler will take care of this for you and will do that more efficiently.
For instance:
Code:
signed char signed8 = -7;
int signed16 = (int)signed8;
will correctly give signed16 = -7

If your data comes form a stream, read it in a signed 8-bit variable first and cast it to a signed 16-bit. This can also be done in a step, like this:
Code:
int signed16 = (int)((signed char)data[i]);
Doing this you'll never need to hear about 2's complement again!

Arthur

Status
Not open for further replies.