串联不同长度的二进制数 [英] Concatenate binary numbers of different lengths

查看:178
本文介绍了串联不同长度的二进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,我有3个数字。一个是字符,另外两个是 int16_t (又名 S,但根据表,我发现短裤就不能可靠地为16位)。

我想将它们串联在一起。所以说,他们的价值观是:

10010001

1111111111111101

1001011010110101

我想和落得一个长长包含:

1001000111111111111111011001011010110101000000000000000000000000

使用一些解决方案,我在网上找到的,我想出了这一点:

  long long结果;
结果= NUM​​1;
结果=(结果<< 8)| NUM2;
结果=(结果<< 24)| NUM3;

但它不工作;这让我很奇怪的数字时,它的德codeD。

在情况下,有一个与我的解码code的一个问题,那就是:

 字符NUM1 = NUM​​&安培; 0xFF的;
int16_t NUM2 = NUM​​<< 8和; 0xFFFF的;
int16_t NUM3 = NUM​​<< 24安培; 0xFFFF的;

这是怎么回事?我怀疑它有一个长长,但我不能完全换我的头周围,我要容纳更多的号码后来<大小做/ p>

解决方案

要得到正确的位模式为你的要求,你使用768,16:

 结果= NUM​​1;
结果=(结果&LT;&LT; 16)| NUM2;
结果=(结果&LT;&LT; 16)| NUM3;
结果&LT;&LT = 24;

这将产生你所要求的精确位模式,24位在LSB-留底0:

  1001000111111111111111011001011010110101000000000000000000000000

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.

解决方案

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

这篇关于串联不同长度的二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆