Concatenate binary numbers of different lengths

半城伤御伤魂 提交于 2019-12-21 05:26:06

问题


So I have 3 numbers. One is a char, and the other two are int16_t (also known as shorts, but according to a table I found shorts won't reliably be 16 bits).

I'd like to concatenate them together. So say that the values of them were:

10010001

1111111111111101

1001011010110101

I'd like to end up with a long long containing:

1001000111111111111111011001011010110101000000000000000000000000

Using some solutions I've found online, I came up with this:

long long result;
result = num1;
result = (result << 8) | num2;
result = (result << 24) | num3;

But it doesn't work; it gives me very odd numbers when it's decoded.

In case there's a problem with my decoding code, here it is:

char num1 = num & 0xff;
int16_t num2 = num << 8 & 0xffff;
int16_t num3 = num << 24 & 0xffff;

What's going on here? I suspect it has to do with the size of a long long, but I can't quite wrap my head around it and I want room for more numbers in it later.


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/13222374/concatenate-binary-numbers-of-different-lengths

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