Hi I'm a new programmer; I'm having problems with unsigned char. I assign a decimal value of 128 to an unsigned char but when I printf this variable comes out as -128. If I assign 127 it comes out at +127, if I assign 129 it comes out as -129. Even if I assign a value of 127, then add 1 it still comes out as -128. It's definitely an unsigned character but it seems to be acting like a signed char.
unsigned char EncVal8; if(Pin8 == 1) { EncVal8 = 128; /*If Pin 8 is on then the Position Value for this Pin will equal 128 */ }
"...but when I printf..." Almost certainly you have used the wrong format specification in your printf format string. printf doesn't know that you want the value to be treated as unsigned unless you specifically tell it You need to carefully read the whole section on the printf format string in the Keil C51 manual, and note that there are specific issues when using byte values - remember that 'C' assumes that everyting is an int (and probably a signed one at that) unless told otherwise.
In future, if you are having a problem with a statement/function, post the code that is showing the problem. You specifically stated that you had a problem with printf(), but then neglected to show how you were using printf(). As Andrew said, you probably mucked up the format string. If you used %d, then the compiler assumed you meant a signed value. You need to use %ud to tell it the value is unsigned.
Cheers chaps, problem solved. So simple a solution, and sorted in seconds... Thanks Stewart