抓取 8 字节字的高 4 字节
我正在乘以 0x1d400 * 0xE070381D
。
当我在计算器上执行此操作时,结果是 0x00019A4D26950400
当我尝试在 cpp 中实现此操作时,这就是我所拥有的。
long long d;
d = 3765450781 * 1d400;
此代码给出的结果是d = 0x26950400
。 这只是底部的 4 个字节,其他的都发生了什么?
我试图隔离高 4 个字节 0x00019A4D
并将它们保存到另一个变量中。这怎么能做到呢?
如果我可以通过乘法来显示所有 8 个字节,那么我想要隔离高 4 个字节的做法是:
d = d & 0xFF00; //0xFF00 == (binary) 1111111100000000
d = d>>8;
这行得通吗?
I am multiplying 0x1d400 * 0xE070381D
.
When I do this on my calculator the result is 0x00019A4D26950400
When I tried implementing this in cpp here's what i have.
long long d;
d = 3765450781 * 1d400;
The result this code gives is that d = 0x26950400
.
This is only the bottom 4 bytes, what happened to everything else?
I am trying to isolate the upper 4 bytes 0x00019A4D
and save them into another variable. How can this be done?
If I could get the multiplication to display all 8 bytes what I was thinking of doing to isolate the upper 4 bytes was:
d = d & 0xFF00; //0xFF00 == (binary) 1111111100000000
d = d>>8;
Will this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在数字后面添加
LL
(例如3765450781LL
),否则它们将被计算为int
,其余部分在分配给之前被截断d。
Add
LL
after the numbers (e.g.3765450781LL
) otherwise they are calculated asint
s and the rest is chopped off before the assignment tod
.您需要在常量后使用
LL
来表示long long
,如 MByD 的另一个答案中所示。此外,您的数据类型应为
unsigned long long
。否则,当右移时,由于符号扩展,最左边的位可能会重复。 (这是与机器相关的,但大多数机器在右移时符号会扩展负数。)您不需要在右移之前屏蔽掉高 4 个字节,因为当您这样做时,无论如何您都会丢弃低 4 个字节右移。
最后,请注意
>>
的参数是要移位的位数,而不是字节数。因此,你想要的也可以写成
You need to use
LL
after your constant for along long
, as indicated in another answer by MByD.In addition, your data type should be
unsigned long long
. Oherwise when you right shift, you may get the leftmost bit repeated due to sign-extend. (That is machine-dependent, but most machines sign extend negative numbers when right shifting.)You do not need to mask off the upper 4 bytes before right shifting, because you are going to throw away the lower 4 bytes any way when you do the right shift.
Finally, note that the argument to
>>
is the number of bits to shift, not bytes. Therefore, you wantWhich can also be written as
正如其他人指出的那样,您必须在 64 位数字文字后面添加
LL
后缀。要以十六进制打印
long long
变量,请使用格式说明符"%016llX"
:输出
00019A4D26950400
。要获取变量
d
的高32位和低32位(4个字节),可以这样做:As the others pointed out, you must suffix your 64-bit numeric literals with
LL
.To print your
long long
variable in hex, use the format specifier"%016llX"
:outputs
00019A4D26950400
.To get the upper and lower 32 bits (4 bytes) of the variable
d
, you can do: