[英]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? 我知道这与第一个为1使其成为负数有关,也许默认情况下它尝试将其打印为int
? Making the char
unsigned
does not change this, however. 但是,将char
unsigned
并不会改变这一点。
This is inspired by @Ben's comments on the question. 这是受到@Ben对问题的评论的启发。 It appears that Serial.println((unsigned char)b, BIN);
看来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. char
在您的计算机上似乎是签名类型。 That means when yout pass it to println
, which expects an int
, it gets sign-extended to the value you see there. 这意味着,当您将其传递给println
(期望int
,它将被符号扩展为您在此处看到的值。 Use a cast as suggested in other answers or switch to unsigned char
. 使用其他答案中建议的强制转换,或切换到unsigned char
。
Edit: I noticed your post says that using unsigned
doesn't help. 编辑:我注意到您的帖子说使用unsigned
并没有帮助。 That might indicate that the API is doing something funny internally. 这可能表明该API在内部做了一些有趣的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.