gpt4 book ai didi

C++ 对齐/移位问题

转载 作者:搜寻专家 更新时间:2023-10-31 00:03:54 24 4
gpt4 key购买 nike

我有一个字符串:

"the quic"

它被传递给一个函数,其中构成字符串的位存储在一个无符号的 __int64 中。产生以下输出:

0111010001101000011001010010000001110001011101010110100101100011

但是当我传递一个包含这些值的字符串时:

0xDE, 0x10, 0x9C, 0x58, 0xE8, 0xA4, 0xA6, 0x30, '\0'

输出不像我预期的那样正确:

1111111111111111111111111111111111111111111111111010011000110000

我使用的代码与第一个字符串中的相同,内容为:

(((unsigned __int64)Message[0]) << 56) | (((unsigned __int64)Message[1]) << 48) |
(((unsigned __int64)Message[2]) << 40) | (((unsigned __int64)Message[3]) << 32) |
(((unsigned __int64)Message[4]) << 24) | (((unsigned __int64)Message[5]) << 16) |
(((unsigned __int64)Message[6]) << 8) | (((unsigned __int64)Message[7]));

最佳答案

我猜你做过这样的事情,

char a[] = {0xDE, 0x10, 0x9C, 0x58, 0xE8, 0xA4, 0xA6, 0x30};

将其更改为 unsigned char 将解决您的问题,

unsigned char a[] = {0xDE, 0x10, 0x9C, 0x58, 0xE8, 0xA4, 0xA6, 0x30};

我都试过了,char 版本在 VC++ 中是错误的,但 unsigned 版本是正确的。

如果你想知道原因,看一个更简单的版本,

char a = 0xDE;
unsigned char b = 0xDE;

有什么区别? 0xDE 是一个 int 类型。对于第一个,您将 int 转换为 signed char,对于第二个,您将 int 转换为 unsigned char。

来自标准 4.7/2、4.7/3

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]

关于C++ 对齐/移位问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5178330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com