Concatenate binary numbers of different lengths

丶灬走出姿态 提交于 2019-12-03 16:05:58

To get the correct bit-pattern as you requested, you shoud use:

result = num1;
result = (result << 16) | num2;
result = (result << 16) | num3; 
result<<=24;

This will yield the exact bit pattern that you requested, 24 bits at the lsb-end left 0:

1001000111111111111111011001011010110101000000000000000000000000

For that last shift, you should only be shifting by 16, not by 24. 24 is the current length of your binary string, after the combination of num1 and num2. You need to make room for num3, which is 16 bits, so shift left by 16.

Edit:

Just realized the first shift is wrong too. That should be 16 also, for similar reasons.

Yes you are overflowing the value that can be stored in long. You can use a arbitrary precison library to store the big number like the GMP.

If I understand correctly what you are doing, I would use:

result = num1;
result = (result << 16) | num2;
result = (result << 16) | num3;

num1out = (result >> 32) & 0xff;
num2out = (result >> 16) & 0xffff;
num3out = result & 0xffff;

The left shift during building is by the width of the next number to insert. The right shift on extraction is by the total number of bits the field was left shifted during building.

I have tested the above code. long long is wide enough for this task with the g++ compiler, and I believe many others.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!