Unsigned int to signed int conversion

Thread Starter

aamirali

Joined Feb 2, 2012
412
I have uint16_t type of data from ADC conversion register, which can take value from 0 - 30000. This is after multiplication by some constant.

Now I have to print it on graph, & have to level shift from mid point so I got negative value range i.e -15000 to +15000.

What should be correct conversion method like

uint16_t val;

int16_t conv_val;

if( val > 32767 )

{

val = 32767; /* limit it for avoiding saturation as conversion to signed is needed */

}

conv_val = (int16_t)val; //is it correct way
 

WBahn

Joined Mar 31, 2012
29,976
No, that won't do anything. You have already limited val to be a 15-bit positive integer and 15-bit positive integers are represented the same way in a 16-bit signed or a 16-bit unsigned integer.

How would you do it manually?

If I told you that val=1000, what value would you plot on the graph?

If I told you that val=29000, what value would you plot on the graph?

If I told you val=x, what value would you plot on the graph?
 

Thread Starter

aamirali

Joined Feb 2, 2012
412
I now conder 15000 as origin & then print values accordingly. So 30000 is +15000 on graph & 0 is -15000 on graph.

Before printing I have to divide by constant & signed factor that why I am asking how to cnvert unsigned into signed
 

RamaD

Joined Dec 4, 2009
328
Convert to signed, as your max value of 30000 is within int16, and subtract 15000. Unsigned integers cannot hold negative numbers.
I do not know how your graph plotting is, you could also simply plot with 0-30000, and draw the axis (zero) at 15000!
 

WBahn

Joined Mar 31, 2012
29,976
I now conder 15000 as origin & then print values accordingly. So 30000 is +15000 on graph & 0 is -15000 on graph.

Before printing I have to divide by constant & signed factor that why I am asking how to cnvert unsigned into signed
What constant do you think you have to divide by.

Again, what mathematical operation do you need to perform to change 15000 to 0, 30000 to 15000, and 0 to -15000?

uint x
int y

y = ???? (what mathematical expression involving x)
 
Top