Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Help : Converting 8 bit to 16 bit

Status
Not open for further replies.

Maverickmax

Advanced Member level 1
Joined
Dec 6, 2004
Messages
404
Helped
8
Reputation
16
Reaction score
3
Trophy points
1,298
Activity points
3,691
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
Joined
Apr 4, 2009
Messages
81
Helped
15
Reputation
30
Reaction score
9
Trophy points
1,288
Location
Perth
Activity points
1,791
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
Joined
Nov 28, 2003
Messages
131
Helped
49
Reputation
98
Reaction score
36
Trophy points
1,308
Location
Stockholm, Sweden
Activity points
1,218
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.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Top