开发者

grabbing upper 4 bytes of a 8 byte word

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?开发者_Python百科

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?


Add LL after the numbers (e.g. 3765450781LL) otherwise they are calculated as ints and the rest is chopped off before the assignment to d.


You need to use LL after your constant for a long 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 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.

To print your long long variable in hex, use the format specifier "%016llX":

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

outputs 00019A4D26950400.

To get the upper and lower 32 bits (4 bytes) of the variable d, you can do:

unsigned int upper;
unsigned int lower;

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜