How to convert unsigned to signed char (and back) while preserving range in C? -
How to convert unsigned to signed char (and back) while preserving range in C? -
i have situation need convert unsigned char (0-255) signed char (-128-127). want have 0 converted -128, 127 converted 0 , 255 converted 127.
i using code (even though won't preserve range entirely):
unsigned char convertunsigned(char n) { homecoming n + 127; } char convertsigned(unsigned char n) { homecoming n - 127; }
this code appears taking values , converting them 255, can't verify (see below).
i writing vex pic microcontroller (which has microchip picmicro pic18f8520) using mplab c18 compiler. can't tell code doing because have no debugger or other way communicate code on chip.
the compiler supports c89 , not automatically promote operands ints (see the manual, section 2.7.1) normal c compilers, might part of problem.
updatethe application writing works this:
get unsigned char represents joystick axis (255 = total forward, 0 = total backward, center = ~127/128 [the documentation not state specifically]) convert char usingconvertsigned(n)
do math calculate motor speed (i have eliminated step testing). convert unsigned char motor (same range joystick, except documentation explicitly states center value 127), using convertunsigned(n)
.
i think want:
unsigned char convertunsigned(char n) { homecoming (int)n + 128; } char convertsigned(unsigned char n) { homecoming (int)n - 128; }
assuming "127 converted 0" typo.
c unsigned signed mplab
Comments
Post a Comment