简体   繁体   English

C以字节为单位存储位的编程

[英]C Programming on storage of bits in byte

#include<stdio.h>

int main()
{
    char a = 128;
    char b = -128;
    printf("a is %d -- b is %d \n",a,b);

    return 0;
}

The output is : 输出为:

a is -128 -- b is -128

As the signed character range is from 0 to 127, from the above code can you please explain how the value is assigned for the out of boundary values. 由于有符号字符的范围是0到127,因此您可以根据上述代码说明如何为超出边界的值分配该值。

Thanks in Advance. 提前致谢。

The range of a char type depends on the implementation. char类型的范围取决于实现。 If it is a signed type, then its range is at least from -128 to 127, and if it is an unsigned type its range is at least from 0 to 255 (these are the ranges that the type must support at a bare minimum, the range supported by the type may actually be larger than this depending on the implementation). 如果是有符号类型,则其范围至少为-128至127,如果是无符号类型,则其范围至少为0至255(这些是该类型必须至少支持的范围,类型所支持的范围实际上可能大于此范围,具体取决于实现方式)。

Also note, that when you assign an integer to a signed type that cannot hold that value, you are invoking undefined behaviour . 还要注意,当您为不能容纳该值的带符号类型分配一个整数时,您正在调用未定义的行为 So assigning 128 to a signed char that cannot hold 128 (eg when 128 is greater than CHAR_MAX ) is invoking undefined behaviour. 因此,将128分配给不能容纳128的带符号的char(例如,当128大于CHAR_MAX )会调用未定义的行为。 In this case, it has wrapped around to -128 because it shares the same byte representation as an unsigned char type holding 128, but as with all instances of undefined behaviour, you cannot guarantee that this will be the case on all implementations. 在这种情况下,它包装到-128因为它与保存128的无符号字符类型共享相同的字节表示,但是与所有未定义行为的实例一样,您不能保证在所有实现中都是如此。

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

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