简体   繁体   English

如何将一个数组值合并为一个整数 C++

[英]how can merge one array values in one integer c++

如何将一个数组值合并为一个整数并颠倒?

example: a[]=0b1011,0b1111 to 10111111 and 10010101 to b[]=0b1001,0b0101

You need to covert types so that the values so they can hold 8 bits (a char or uint8 would do depending on what you need).您需要隐藏类型,以便这些值可以容纳 8 位(char 或 uint8 将根据您的需要执行)。 I'm not sure what type you have there as its 4 bits.我不确定你在那里有什么类型的 4 位。 You're better off redefining the type to be a uint8 or something so a[0] = 0b00001011.您最好将类型重新定义为 uint8 或其他类型,例如 a[0] = 0b00001011。

Once you have the right number of bits need to bitshift the first value left by 4, then use the bitwise OR operator, taking your example,一旦你有正确的位数需要将第一个值左移 4,然后使用按位 OR 运算符,以你的为例,

int8 myValue = a[0] << 4 | a[1]

Here's whats going on这是怎么回事

  • Bitshift: a[0] << 4 means move every bit to the left 4 times so 0b00001011 becomes 0b10110000 (bits coming into the right default as 0)位移:a[0] << 4 表示将每个位向左移动 4 次,因此 0b00001011 变为 0b10110000(位进入右侧默认为 0)
  • Bitwise OR: a[0] << 4 |按位或:a[0] << 4 | a[1], the | a[1], | compares every bit from a[0] with a[1].将 a[0] 中的每一位与 a[1] 进行比较。 If either on of the bits are 1's it gives a 1, if both are 0, it gives a 0 ie如果任一位为 1,则为 1,如果均为 0,则为 0,即

    10110000 | 10110000 | 00001111 = 10111111 00001111 = 10111111

By upside down I assume you mean in reverse?颠倒我假设你的意思是相反?

You'll need to use the bitwise AND &, and do something similar so I wont explain in detail again, but its this你需要使用按位 AND &,并做一些类似的事情,所以我不会再详细解释了,但它的这个

a[0] = (myValue & 0b1111000) >> 4 = 00001011

a[1] = myValue & 0b00001111 = 00001111

Hope that helps.希望有帮助。

<< and | <<| to "paste" two integers together, >> and & to take them apart.将两个整数“粘贴”在一起, >>&将它们分开。

For instance, (3 << 4) | 5例如, (3 << 4) | 5 (3 << 4) | 5 is 53, 53 >> 4 is 3, 53 & 7 is 5. (3 << 4) | 5是 53, 53 >> 4是 3, 53 & 7是 5。
(Translating the integers to binary notation left as an exercise.) (将整数转换为二进制符号留作练习。)

tnq for help,i want a code to do this tnq 寻求帮助,我想要一个代码来做到这一点

a[]={1,2,3,5,8,6,7,4};
result=a[0,1,2,3]+a[4,5,6,7];
result-->9909

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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