Quote:
Originally Posted by Tom Line
My team wants to subtract 127 from each joystick to change the range from 0 to 255 to -127 to 127. We originally had trouble with this statement:
x_joy_1 = p1_x - 127; // Makes the range -127 to 127
y_joy_1 = p1_y - 127;
p1_x is a defined term from the rcdata. x_joy_1 is an int. I'm not precisely sure why we had trouble - I suspect it's because p1_x is of the wrong type (it's a define, not an int).
Changing it as one of the team members suggested:
int(p1_x) and int(p1_y) resulted in a syntax error.
|
The correct syntax is
(int)p1_x. This is called "type casting".
Try this:
Code:
x_joy_1 = (int)p1_x - 127; // Makes the range -127 to 127
y_joy_1 = (int)p1_y - 127;
Quote:
Originally Posted by Tom Line
Could someone shine some light on why this works the way it does? I'm sick of trial and error with variable int types Isn't there a much more elegant way of coding this?
|
The problem you're facing is one of one of order of operations. Consider this statement: 5 + 5 * 5. What is the value? Is it 50 or 30? If you do the addition first, you'll get 10 * 5 = 50. If you do the multiplication first, you'll get 5 + 25 = 30. In C, multiplication is defined to come before addition.
In the statement above,
x_joy_1 = p1_x - 127, everything to the right of the equals sign is evaluated before the assignment operator (i.e. the equals sign). First the compiler does
p1_x - 127. p1_x is an
unsigned char which means it has a range of 0-255. Suppose it had a value of 122. Now, when you subtract 127, you get -5. However, since that is outside of the range for its type, it wraps around, and so you get 250. Next comes the assignment operator.
x_joy_1 is of type
int, while the value on the right is an
unsigned char. The compiler now automatically typecasts the value on the right to be the same type as the variable on the left, in order to do the assignment.
What you want to do is make sure that the value on the right is an
int before the subtraction operator happens. To do this, you typecast the unsigned char to an int with the statement
(int)p1_x.
Quote:
Originally Posted by Tom Line
p1_x is of the wrong type (it's a define, not an int)
|
While p1_x is "a define", that is not a type. To find out what type it is, you have to see what it's defined as. It's defined as something which has a type of unsigned char.