# how to easily make u12 into u16 with sign extension?

Status
Not open for further replies.

#### sweethomela8

##### Member level 4 Hi, whats the easiest way to transform a 12 bit unsigned variable into a 16 bit unsigned variable where the additional 4 bits equal to the 12th bit of the original variable? (sign extension)

ie. 0xF0A -> 0xFF0A
ie. 0xA12 -> 0xFA12
ie. 0x612 -> 0x0612

thanks.

In the C programming language.

#### andre_teprom

##### Super Moderator
Staff member Check if operation bellow works :

Code:
Value = Value | ( 15 * 256 * 256 * 256 ) ; // Shift left 3 nibles
You can declarte it like constant (#define .... ).
I just posted this way to clarify.

+++

#### alexan_e You can do it using typecasting, when you shift a signed number the sign is preserved (arithmetic shift)

Code C - [expand]1
2
3
4
volatile unsigned int x;

x=0xF0A;
x=((signed int)x<<4)>>4;  // shift left 4 bits so that bit11 goes to bit15 as sign and then shift right 4 and the "sign" will be preserved

Alex

#### horace1 the following is OK if >> is arithmetic shift
Code:
x=((signed int)x<<4)>>4;
it will not work if >> is logical (the C standard does not specify if >> is arithmetic or logical shift it is implementation dependent)
try
Code:
    y = y | ((y & 0x800) << 1) | ((y & 0x800) << 2) | ((y & 0x800) << 3) | ((y & 0x800) << 4);
or
Code:
   if(y & 0x800) y |= 0xf000;

Status
Not open for further replies.