There are two totally separate issues here.
Issue number 1:
Hi There,
I have some code that reads inputs from an exterior source, for sum reason it randomly sends nagative numbers should be 128 buts its -128 for example.
Hex value should 0x80 its 0xffffff80.
This is caused by assigning a signed char to an int or unsigned int. doing that invokes "sign extension". The original variable held a negative value and the assignment sought to preserve that value.
If you don't want sign extension to occur then you need to cast to an unsigned type of the same size first.
e.g.
Code:
signed char c = 0x80;
unsigned int i1 = c; // i1 will be 0xFFFFFF80
unsigned int i2 = (unsigned char)c; // i2 will be 0x00000080
However, for clarity you should ideally be doing two casts, one to change the signedness and one to change the size, hence:
Code:
unsigned int i3 = (unsigned int)(unsigned char)c; // i3 will be 0x00000080
Note that if you try and do it with just the one cast to unsigned int then you're actually doing the same thing as the i1 case, i.e.
Code:
unsigned int i4 = (unsigned int)c; // i4 will be 0xFFFFFF80
Happy casting!
Issue number 2:
What is the easiest way of making a condition.
If(Feedback = 80 or -80). For example.
this is simply asking how to write code such as:
Code:
if (feedback == 80 || feedback == -80)
in a shorter form.
There are two ways to do this: One is to use an abs function. It then becomes:
Code:
if (abs(feedback) == 80)
The other way is if you want the two values to be like 70 and -90 or any other different values, then you need to make a function that takes all three arguments and just call that:
Code:
int equals_any(int value, int test1, int test2) {
return value == test1 || value == test2;
}
...
if (equals_any(feedback, 70, -90))
Note how this doesn't actually save you from having to write it out the long way, but you can at least just do that inside the function in one place.
Lastly Libpgeak, a modern PC does not used signed-magnitude representation. Simply clearing the top bit does not perform the absolute value function. It undisputably will change the number from negative to positive, but the magnitude may be different afterwards. Simple example:
-1 in a byte is 0xFF. Flip the top bit and you now have 0x7F. It's positive alright, but it's equal to 127!