Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从大端到小端转换c++;_C++_Endianness - Fatal编程技术网

C++ 从大端到小端转换c++;

C++ 从大端到小端转换c++;,c++,endianness,C++,Endianness,我正在做一个家庭作业,打印出int和float的大小端值。我很难转换成小恩迪安 这是我的密码 void convertLitteE(string input) { int theInt; stringstream stream(input); while(stream >> theInt) { float f = (float)theInt; printf("\n%d\n",theInt); print

我正在做一个家庭作业,打印出
int
float
的大小端值。我很难转换成小恩迪安

这是我的密码

void convertLitteE(string input)
{
    int theInt;
    stringstream stream(input);
    while(stream >> theInt)
    {
        float f = (float)theInt;

        printf("\n%d\n",theInt);
        printf("int:   0x");
        printLittle((char *) &theInt, sizeof(theInt));

        printf("\nfloat: 0x");
        printLittle((char *) &f, sizeof(f));
        printf("\n\n");
    }
}

void printLittle(char *p, int nBytes)
{
    for (int i = 0; i < nBytes; i++, p++)
    {
        printf("%02X", *p);
    }
}
但当输入为1234时

output:
int:   0xFFFFFFD20400000
float: 0x0040FFFFFFF9A44
但我希望

output:
int:   0x0C000000
float: 0x00004041
int :  0xD2040000
float: 0x00409A44
当我通过
for
循环时,我可以看到哪里似乎有垃圾值,然后它会打印所有的
F
,但我不知道为什么。我尝试过很多不同的方法,但都没能成功


非常感谢您的帮助。

显然,在您的系统中,
char
是一种有符号的8位类型。使用无符号8位字节,1234的4字节小尾端表示将是
0xd2、0x04、0x00、0x00
。但在大多数系统上,当解释为有符号的
char
时,
0xd2
变为
-0x2e

然后调用
printf
char
提升为
int
,值为
-0x2e
,然后
printf
(不太安全)读取传递
int
无符号int
。这是未定义的行为,但在大多数系统上,它将与静态转换相同,因此在尝试打印第一个字节时,您将获得值
0xFFFFFFD2

如果在这些函数中坚持使用
unsigned char
而不是
char
,则可以避免此特定问题


(但正如@jogojapan所指出的,整个方法根本无法移植。)

我使用字符串,因为我们必须能够一次输入多个数字。所以我只需要使用getline,然后从字符串中获取数值。这是什么语言?C++?您需要用正在使用的语言标记您的问题。@Jeff它看起来像是
convertlettee
应该从十进制字符串转换为小端十六进制输出。该部分没有根本问题。您的方法似乎是逐个打印
int
的内部表示的字节。这并不能保证给你一个小小的endian整数表示。它将给出系统对整数使用的任何表示。@jogojapan true,但是对于这个家庭作业,我假设系统是big-endian。