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_teprom

Super Moderator
Staff member
Joined
Nov 7, 2006
Messages
9,299
Helped
1,161
Reputation
2,341
Reaction score
1,151
Trophy points
1,403
Location
Brazil
Activity points
54,164
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,895
Helped
2,021
Reputation
4,158
Reaction score
2,032
Trophy points
1,393
Location
Greece
Activity points
64,375
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,123
Helped
596
Reputation
1,188
Reaction score
573
Trophy points
1,393
Location
Norwich, UK
Activity points
13,069
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.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Top