简体   繁体   中英

Arduino Serial.print(, BIN) odd behavior

Code:

char a = 0x70;
char b = 0x80;

Serial.println(a, BIN); // Should print  1110000
Serial.println(b, BIN); // Should print 10000000

Output:

1110000
11111111111111111111111110000000

I know this has something to do with the first bit being one makes it a negative number and maybe it tries to print it as an int by default? Making the char unsigned does not change this, however.

This is inspired by @Ben's comments on the question. It appears that Serial.println((unsigned char)b, BIN); gets the desired output.

Here is my complete sketch:

void setup() {
  Serial.begin(9600);
  // Confirm observations from question
  char a = 0x70;
  char b = 0x80;

  long aPrint = Serial.println(a, BIN); // Should print  1110000
  long bPrint = Serial.println(b, BIN); // Should print 10000000

  // Output println results (Ben comment #1)
  Serial.print("aPrint: ");
  Serial.println(aPrint);
  Serial.print("bPrint: ");
  Serial.println(bPrint);

  // Explicit cast from char
  Serial.print("(int)b: ");
  Serial.println((int)b);

  // Via unsigned char
  Serial.print("(unsigned char)b: ");
  Serial.println((unsigned char)b);
  // And print in binary
  Serial.println((unsigned char)b, BIN);
}

void loop() {
}

Output:

1110000
11111111111111111111111110000000
aPrint: 9
bPrint: 34
(int)b: -128
(unsigned char)b: 128
10000000

char appears to be a signed type on your machine. That means when yout pass it to println , which expects an int , it gets sign-extended to the value you see there. Use a cast as suggested in other answers or switch to unsigned char .

Edit: I noticed your post says that using unsigned doesn't help. That might indicate that the API is doing something funny internally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM