简体   繁体   English

二进制函数的字符无法正常工作

[英]Character to binary function doesn't work as expected

I have made a function to translate a number to its binary form: 我做了一个函数,将数字转换为二进制形式:

size_t atobin (char n)
{
    size_t bin= 0, pow;
    for (size_t c= 1; n>0; c++)
    {
        pow= 1;
        for (size_t i= 1; i<c; i++) //This loop is for getting the power of 10
            pow*= 10;
        bin+= (n%2)*pow;
        n/= 2;
    }
    return bin;
}

It works great for numbers 1 to 127, but for greater numbers (128 to 255) the result is 0... I've tried using the type long long unsigned int for each variable but the result was the same. 它适用于1到127的数字,但适用于更大的数字(128到255),结果为0 ...我尝试为每个变量使用long long unsigned int类型,但结果相同。 Someone has an idea about why? 有人对为什么有想法?

char by default in C is considered to be of signed. 默认情况下,C中的char被认为是带符号的。

char is of 8 bits(mostly). char是8位(大部分)。 And for signed char the MSB is used for sign. 对于签名的字符,MSB用于签名。 As a result you can only use 7 bits. 结果,您只能使用7位。

( 0111 1111 ) 2 = ( 127 ) 10 The maximum value that your fucntion can work with. 0111 11112 =( 12710功能可以使用的最大值。 (as you are passing a type of variable which can hold 127 at max). (因为您要传递的变量类型最多可容纳127 )。

If you use unsigned char then the MSB is not used as sign-bit. 如果使用无符号字符,则不将MSB用作符号位。 All 8 bits are used giving us a maximum possible value ( 1111 1111 ) 2 = ( 255 ) 10 全部使用了8位,从而为我们提供了最大可能值( 1111 11112 =( 25510

For signed number min/max value is -127 to +127 . 对于有符号数,最小值/最大值是-127+127

For unsigned number min/max value is 0 to +255 . 对于无符号数,最小/最大值为0+255

So even if you make the type of the passed parameter unsigned char the maximum value it can hold is +255 . 因此,即使您将传递的参数的类型设置为unsigned char ,它可以容纳的最大值为+255


A bit more detail: 更详细一点:

Q) What happens when you assign >127 values to your char parameter? 问)char参数分配>127值时会发生什么?

It is signed char by default. 默认情况下,它是签名的char。 It is of 8 bits. 它是8位。 But it can't hold it. 但它不能容纳它。 So what will happen? 那么会发生什么呢?

The result is implementation defined. 结果是实现定义的。 But

Suppose the value is 130 . 假设值为130 In binary it is 10000010 . 二进制为10000010 In most of the cases this returns -126 . 在大多数情况下,返回-126 So that will be the value of n . 所以那将是n的值。 n>0; fails. 失败。 Loop is never entered. 永远不会进入循环。 And it returns 0 . 并返回0


Now if we make it unsigned char then it can hold values between 0 and 255 (inclusive). 现在,如果我们将其设置为无符号字符,则它可以容纳0到255(含)之间的值。 And that is what you want to have here. 这就是您想在这里拥有的。


Note: 注意:

Q) What happens when >255 values are stored in unsigned char? 问) >255值存储在无符号字符中时会发生什么?

The value is reduced to modulo of (max value unsigned char can hold+1) which is 256. 该值减少为256 (max value unsigned char can hold+1)模。

So apply modulo operation and put the result. 因此,应用模运算并得出结果。 That will be stored in unsigned char. 它将存储在未签名的char中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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