0

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 i.e. "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.

8
  • In what way does it "not work"? Can you express mathematically what function you're hoping to accomplish? Or express it in terms of bit strings? Commented Mar 7, 2015 at 5:01
  • I repeat my previous comment. :P Are you trying to make c be the integer whose (two's complement) binary representation is the concatenation of the binary representations of a and b (both extended to be 32 binary digits long)? Commented Mar 7, 2015 at 5:13
  • @Hurkyl thanks for your comments. Is the new edit clearer ? Commented Mar 7, 2015 at 5:20
  • did you mean c |= b on the last line? Better question: what do you expect the answer to be if a = -1 and b = 50? Commented Mar 7, 2015 at 5:21
  • @clemej: Yes, that is his problem. When he does addition, the 32nd bit will be zero and so he'll get a large negative number. Commented Mar 7, 2015 at 5:24

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Hat tip to @Hurkyl 's comment above that reminded me you may need a explicit cast to 32 bit to keep a negative 32-bit value from being sign extended to 64-bits before the bitwise or.
Thanks you so much this was perfect. I know my question was very very confusing. But your answer was spot on. I owe my hours and hours of time saved to you !!!!!
note: += vs. |= makes no difference if the lower 32 bits of c are 0 and we are using 2's complement (as OP's code relies on anyway)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.