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.

update

the 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 using convertsigned(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

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -