简体   繁体   English

抓取8字节字的高4字节

[英]grabbing upper 4 bytes of a 8 byte word

I am multiplying 0x1d400 * 0xE070381D . 我乘以0x1d400 * 0xE070381D

When I do this on my calculator the result is 0x00019A4D26950400 当我在计算器上执行此操作时,结果为0x00019A4D26950400

When I tried implementing this in cpp here's what i have. 当我尝试在cpp中实现这个时,我就拥有了。

long long d;

d = 3765450781 * 1d400;

The result this code gives is that d = 0x26950400 . 该代码给出的结果是d = 0x26950400 This is only the bottom 4 bytes, what happened to everything else? 这只是底部的4个字节,其他一切都发生了什么?

I am trying to isolate the upper 4 bytes 0x00019A4D and save them into another variable. 我试图隔离高4字节0x00019A4D并将它们保存到另一个变量。 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: 如果我可以得到乘法显示所有8个字节,我想要做的是隔离上面的4个字节是:

d = d & 0xFF00; //0xFF00 == (binary) 1111111100000000

d = d>>8;

Will this work? 这会有用吗?

在数字后添加LL (例如3765450781LL ),否则它们将被计算为int s,其余部分在分配给d之前被切断。

You need to use LL after your constant for a long long , as indicated in another answer by MByD. 你需要在常数之后long long使用LL ,如MByD的另一个答案所示。

In addition, your data type should be unsigned long long . 此外,您的数据类型应该是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. 您不需要在右移之前屏蔽高4字节,因为当您进行右移时,您将以任何方式丢弃低4字节。

Finally, note that the argument to >> is the number of bits to shift, not bytes. 最后,请注意>>的参数是要移位的位数 ,而不是字节。 Therefore, you want 因此,你想要

d = d >> 32;

Which can also be written as 哪个也可以写成

d >>= 32;

As the others pointed out, you must suffix your 64-bit numeric literals with LL . 正如其他人所指出的那样,您必须使用LL后缀64位数字文字。

To print your long long variable in hex, use the format specifier "%016llX" : 要以十六进制格式打印long long变量,请使用格式说明符"%016llX"

long long d;
d = 3765450781LL * 0x1d400LL;
printf("%016llX\n", d);

outputs 00019A4D26950400 . 输出00019A4D26950400

To get the upper and lower 32 bits (4 bytes) of the variable d , you can do: 要获得变量d上下32位(4个字节),您可以执行以下操作:

unsigned int upper;
unsigned int lower;

upper = d >> 32;
lower = d & 0x00000000FFFFFFFF;

printf("upper: %08X lower: %08X\n", upper, lower);

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

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