简体   繁体   中英

How to convert 2 signed 32 bit numbers to 64 bit in C

a and b are upper half and lower half of the same number. Now I have to save this number to a 64 bit register. lets say a = -1(Higher bytes) and b = -50. How can I do this ?

I am using the following which works for positive numbers.

int64_t c = (a);
c = (c<<32);
c+=b;

The above does not work for -ve numbers. How to do this ?

Edit: The above code for -ve numbers give a very large value for the -50. Basically what this means is that after the operation the "c" should have the value of -50, but it should be 64 bits. As upper half ie "a" is -1 and acts as the signed bit. The lower half has a -ve sign which makes it value very large due to the shifting operation. I hope this is a little more clear.

Assuming you mean to do straight bitwise replacement without sign extension, then I think you want to replace

c += b;

in your code with

c |= (uint32_t)b; 

For a = -1 and b = -50,this will make c = 0xffff.ffff.ffff.ffce

For a = -1 and b = 50, this will make c = 0xffff.ffff.0000.0032

For a = 1 and b = -50, this will make c = 0x0000.0001.ffff.ffce

For a = 1 and b = 50, this will make c = 0x0000.0001.0000.0032

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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