从8位字节中提取二进制数据并将其转换为基本类型[c++]
extracting binary data out of 8-bit byte and converting it to primitive types [C++]
我有一个整数向量vector<int>
,其中有48个项目。我想从中提取二进制数据(不确定这是否是正确的方式来调用它,请编辑它,如果它是错误的),即一个或多个位的序列,然后将它们转换为像int这样的基本类型。我想到了这样一个解决方案:
int extractValue(vector<int> v, int startBit, int endBit) {
int beginByteIndex = (startBit / 8);
int endByteIndex = (endBit / 8);
vector<bool> bits;
bits.clear();
int startIndex = startBit % 8;
int endIndex = endBit % 8;
int value = v[beginByteIndex];
value = (value << startIndex);
int temp = 8;
if (beginByteIndex == endByteIndex) {
temp = endIndex + 1;
}
for (int i = startIndex; i < temp; i++) {
int temp = 0x80 & value;
bits.push_back(temp);
value <<= 1;
}
for (int i = beginByteIndex + 1; i < endByteIndex; i++) {
value = v[i];
for (int j = 0; j < 8; j++) {
int temp = 0x80 & value;
bits.push_back(temp);
value <<= 1;
}
}
if (endByteIndex > beginByteIndex) {
value = v[endByteIndex];
for (int i = 0; i <= endIndex; i++) {
int temp = 0x80 & value;
bits.push_back(temp);
value <<= 1;
}
}
int size = bits.size();
int p = 1;
int result = 0;
for (int i = size - 1; i >= 0; i--) {
result += (bits[i] * p);
p *= 2;
}
return result;
}
,但是这个函数很长,难以阅读,并且是用C语言完成的。有人可以建议一个c++的方式做到这一点。我几乎可以肯定c++有一种很好的、简短的、优雅的方法来实现这一点。也请编辑问题,这样其他有类似问题的人可以从中受益。遗憾的是,我的英语不太好,无法用更一般的方式表达出来。
编辑:例如,我想提取以下信息与以下位置和长度:
int year = extractValue(data, 0, 6);
int month = extractValue(data, 7, 10);
int day = extractValue(data, 11, 15);
一个简单的解决方案:
- 将每个字节转换为十六进制字符串(
ostringstream
或sprintf
甚至可以帮助),您得到2位数字,范围为0到f -
对于每个十六进制数字,您可以像这样创建位图:
0 = 0000;1 = 0001;2 = 0010;…,F = 1111,
-
根据位图向矢量添加位
-
恢复-您采取4位并将其转换回数字,然后采取2位并转换回字节(例如通过将0x添加到十六进制,
isringstream
到字节)。
相关文章:
- 无法转换类型 C++
- 包含可变参数包的第一个可转换类型的别名的结构
- 将 std::conditional 与不可转换类型(原始与指针)一起使用
- 链接方法时出现转换类型错误
- 如何避免隐式转换类型
- 在多重继承场景中动态强制转换类型
- 编译器不支持的转换类型
- 错误调用功能无法转换类型
- 我想看到一个在整个后缀表达式的上下文中查找转换类型 id 的示例
- 对于动态类型为强制转换类型的对象,dynamic_cast失败
- 无法在初始化中转换类型
- 如何让"auto"转换类型
- 如何通过强制转换类型指针将字符数组转换为uint16_t
- 如何从新运算符+(Template类)返回具有转换类型的对象
- 带有模板的基于枚举的工厂无法转换类型
- 使用SWIG类型映射通过字符串转换类型
- 对于可转换类型,设计比循环依赖项更好
- SWIG不能正确转换类型定义
- 将类型转换扩展到可转换类型的对/元组
- 想要将字符数组的部分转换/类型转换为值