简体   繁体   English

为什么该程序的输出意外?

[英]Why is this program's output unexpected?

The following code when executed in eclipse, running on Ubuntu and compiled using g++ compiler, provides unexpected results. 以下代码在eclipse中执行,在Ubuntu上运行并使用g ++编译器进行编译时,会提供意外的结果。

code: 码:

#include <iostream>
int main()
{
    unsigned int a=5555;
    std::cout << (unsigned int)(((char*)&a)[0]) <<  "\n";
    std::cout << (unsigned int)(((char*)&a)[1]) <<  "\n";
    std::cout << (unsigned int)(((char*)&a)[2]) <<  "\n";
    std::cout << (unsigned int)(((char*)&a)[3]) <<  "\n";

  return 0;
}

I am trying to treat the variable a as an array of integers each of one byte size. 我试图将变量a视为一个整数数组,每个整数一个字节大小。 When I execute the program, this is what I get as output: 当我执行程序时,这就是我的输出:

output: 输出:

4294967219
21
0
0

question: 题:

Why is the first value displayed so large (here int is of size 32 bits or 4 bytes). 为什么第一个值显示的太大(此处int的大小为32位或4个字节)。 So each of the output values should obviously be no greater than 255 right? 因此,每个输出值显然都不应大于255,对吗? And why are the last three values zero? 为什么最后三个值都为零? Or why I am getting the wrong result? 还是为什么我得到错误的结果?

I also got the same result when tested in code::blocks, running the same compiler. 在运行相同编译器的code :: blocks中测试时,我也得到了相同的结果。

This because char is a signed integer type. 这是因为char是带符号的整数类型。

Decimal 5555 is hexadecimal 0x15b3 . 十进制5555是十六进制0x15b3

The 0xb3 byte, when sign-extended to a signed int , becomes 0xffffffb3 . 当将0xb3字节符号扩展为一个有signed int ,它变为0xffffffb3

0xffffffb3 interpreted as an unsigned int is 4294967219 in decimal. 解释为unsigned int 0xffffffb3以十进制表示为4294967219。

This is because of sign-extension. 这是由于符号扩展。 Let's look at your unsigned int a in memory: 让我们看看您的unsigned int a内存:

b3 15 00 00

When you cast the first byte from a signed char to an unsigned int , the cast from char to int happens before the conversion from signed to unsigned , and therefore, the sign bit is extended, and the result ( 0xffffffb3 ) is what you see on your first line. 当您将第一个字节从有signed char转换为unsigned int ,从charint的转换发生在从signedunsigned的转换之前,因此,对符号位进行了扩展,结果是( 0xffffffb3 )您的第一行。

Try casting to an unsigned char * instead of a char * . 尝试强制转换为unsigned char *而不是char *

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

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