将位数组转换为short
Convert bit array to short
我有一个函数,它返回short的位(灵感来自将整数转换为位表示):
bool* bitsToShort(short value) {
bool* bits = new bool[15];
int count = 0;
while(value) {
if (value&1)
bits[count] = 1;
else
bits[count] = 0;
value>>=1;
count++;
}
return bits;
}
我该如何做相反的操作?转换短中的位数组?
short shortFromBits(bool* bits) {
short res = 0;
for (int i = 0; i < 15; ++i) {
if (bits[i]) {
res |= 1 << i;
}
}
return res;
}
CCD_ 1将CCD_ 2中的第i个比特设置为1。
像这样:
bool* bits = ... // some bits here
short res = 0;
for (int i = 14 ; i >= 0 ; i--) {
res <<= 1; // Shift left unconditionally
if (bits[i]) res |= 1; // OR in a 1 into LSB when bits[i] is set
}
return res;
本质上:
unsigned short value = 0;
for (int i = sizeof(unsigned short) * CHAR_BIT - 1; 0 <= i; --i) {
value *= 2;
if (bits[i)
++value;
}
这假设bits
指向具有至少sizeof(unsigned short)
个元素的bool
的阵列。我有没有测试它。可能有一个错误。但也许不是。
相关文章:
- 无法从'unsigned short [9]'转换为'char []'
- 有没有一种优雅的方法可以将矢量<复杂<float>>转换为矢量<short>?
- 为什么当将 short[] 转换为字符*时,数组是反转的?
- 将 typedef short 转换为矢量(字符)
- 从“ int”到'int16_t {aka short int}'内部{}的“((int)a) -1)”的缩小转换
- 为什么C/C++会自动将char/wchar_t/short/bool/enum类型转换为int
- 错误:从 'short unsigned int*' 到"短无符号 int"的转换无效|(在 C++ 中)
- wchar_t*到short int的转换
- 将无符号short/int强制转换为char*
- 将位数组转换为short
- 转换 - 错误 E2015,AnsiString(char) 和 AnsiString(short) 之间的歧义
- 将无符号字符转换为 int 和 short
- gcc 奇怪的转换警告(<B>从"int"转换为"A::count_type {aka short unsigned int}"可能会改变其值)
- 将一个short类型数组转换为double类型数组
- 将2D numpy数组转换为c++ short**
- 为什么在C和c++中进行算术运算之前必须将short类型转换为int类型?
- 将unsigned short转换为char
- type conversion-从无符号short转换为字符串c++
- 将"unsigned char"数组转换为其"unsigned short"对应项的有效方法是什么?
- 将 int* 转换为 const short int*