Continue to Site

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.

how to easily make u12 into u16 with sign extension?

Status
Not open for further replies.

sweethomela8

Member level 4
Joined
Apr 28, 2010
Messages
70
Helped
1
Reputation
2
Reaction score
0
Trophy points
1,286
Activity points
1,766
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_luis

Super Moderator
Staff member
Joined
Nov 7, 2006
Messages
9,458
Helped
1,180
Reputation
2,379
Reaction score
1,177
Trophy points
1,403
Location
Brazil
Activity points
54,929
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

Administrator
Joined
Mar 16, 2008
Messages
11,888
Helped
2,021
Reputation
4,158
Reaction score
2,031
Trophy points
1,393
Location
Greece
Activity points
64,371
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

Advanced Member level 5
Joined
Nov 18, 2008
Messages
2,118
Helped
596
Reputation
1,188
Reaction score
571
Trophy points
1,393
Location
Norwich, UK
Activity points
13,063
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.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Top