chipKIT® Development Platform

Inspired by Arduino™

Converting unsigned integer into signed float

Created Tue, 18 Sep 2012 00:53:23 +0000 by Slappy


Slappy

Tue, 18 Sep 2012 00:53:23 +0000

I'm currently using the ChipKit Max32.

Long story short, I'm trying to convert an unsigned integer (e.g. 1110110, or 188) to a signed float, such that it shows as a negative number with digits after the decimal. Problem is: I'm still getting positive values, but in floating decimal. How can I convert them to signed types? Here's a snippet of what I'm doing:

struct IMU{
float in;
} phi, theta, psi;

#define scale 0.0109863

void setup(){
//stuff
}

void loop(){
unsigned int data[6];
int phi_data = 0, theta_data = 0, psi_data = 0;
//Later on, we read data serially from an angular position sensor. This data is assigned to the array cells of data[].
for (byte i = 0; i < 6; i++){
data[i] = Serial1.read();
}
phi_data = ((data[0] << 8) | data[1]);//Concatenate two bytes, comprising one signed integer value
theta_data = ((data[2] << 8) | data[3);
psi_data = ((data[4] << 8) | data[5]);
}

phi.data = float(phi_data)*scale;
theta.data = float(theta_data)*scale;
psi.data = float(psi_data)*scale;
}//end void loop

Any help would be appreciated!


majenko

Tue, 18 Sep 2012 08:33:48 +0000

The pic32 has 32 bit integers. You are using 16 bits. You need to do a sign extend.


rasmadrak

Tue, 18 Sep 2012 08:37:55 +0000

I'm a bit stumped at what you're trying to do exactly - do you want to invert the values?

An integer is 4 bytes, so you never shift beyond the limit with only two bytes. In short - the numbers will always be positive unless shifted further.

--

EDIT:

Majenko beat me to it. :)