The Elektor Forum will close. See also this link. From Friday March 1st it is no longer possible to log in to the forum. However, the content of the forum will remain visible until the end of March. As of April 1st the forum will definitely go off the air.

signed char

An Elektor Distance Learning Course

Postby dirk_999 » Sat Oct 12, 2013 12:00 am

signed char tel;
trisb=00000000;
tel = 120;
tel = tel + 10;
portb = tel;


When i execute this program

port b= (10000010)2 = (130)10

Is this not strange? The maximum capacity of a signed char = 128
I expected (00000001)2
dirk_999
 
Posts: 11
Joined: Thu Jan 02, 2014 10:49 am

Postby geenbert » Sat Oct 12, 2013 12:00 am

Your program works correctly, but it doesn't show what you think it shows. That is because the answer is a signed char, but you read it as an unsigned char, and thus you think it's 130.

A signed char however is just 7 bits, and the 8th bit (the leftmost one) is the sign bit. A signed char with value 0b10000010 is not 130, but -126. Signed chars use the two's a complement method for negative numbers, as described on page 439 (you probably haven't reached that part of the course yet).

When you added 10 to 120 you overflowed the signed char by 3, and thus it rolls over 3 to the low end of its range. For a signed char the range is -128 to 127, so the rollover is to -128.

Like this:
127 + 1 = -128
-128 + 1 = -127
-127 + 1 = -126

So an overflow of 3 results in -126, which is what your program showed.

While you are at it: the table on page 111 states that a signed char is in the range of -128..128, that's a typo and should be -128..127.

BTW numbers with no prefix are assumed to be digital, for binary use 0b (and for hex 0x) as prefix, as used throughout the course.
geenbert
 
Posts: 83
Joined: Thu Jan 02, 2014 10:41 am


Return to Programming Embedded PIC Microcontrollers using Assembly, C and Flowcode

Who is online

Users browsing this forum: No registered users and 1 guest