[英]Conversion between binary and decimal number
I woud like to ask, what bin-'0'
means in this piece of code which convert binary number to decimal. 我想问,在这段将二进制数字转换为十进制的代码中, bin-'0'
是什么意思。 Thanks. 谢谢。
#include <stdio.h>
#include <stdlib.h>
int main(){
char bin;
int dec = 0;
printf("Binary: \n");
bin = getchar();
while((bin != '\n')){
if((bin != '0') && (bin != '1')){
printf("Wrong!\n");
return 0;
}
printf("%c",bin-'0'); // ?
dec = dec*2+(bin-'0'); // ?
bin = getchar();
}
printf("Decimal: %d\n", dec);
return 0;
}
bin - '0'
converts the ASCII value of bin to its integer value. bin - '0'
将bin的ASCII值转换为其整数值。 Given bin = '1'
, bin - '0' = 1
给定bin = '1'
, bin - '0' = 1
This code is taking advantage of the fact that C++ chars are really just special ints. 这段代码利用了C ++字符实际上只是特殊整数的事实。 It's using getchar to take in a char that is either '0' or '1'. 它使用getchar接收一个'0'或'1'的char。 Now it needs to convert that into 0 or 1 (note that these are numbers, not chars). 现在,需要将其转换为0或1(请注意,这些是数字,而不是字符)。 Given that the char '0' is one before '1', subtracting the value of char '0' from both will turn '0' into 0 and '1' into 1. 假设char'0'在'1'之前是1,则从这两个字符中减去char'0'的值会将'0'变成0,将'1'变成1。
'0' - '0' = 0
'1' - '0' = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.