优雅和最短的方法,只保存一半的字节
Elegant & shortest way to save only half of byte
有什么优雅而最短的方法可以做到这一点吗?
unsigned char someInteger(int someInt) {
// 00110110
unsigned char type[7];
type[7] = ((someInt >> 7) & 0x1);
type[6] = ((someInt >> 6) & 0x1);
type[5] = ((someInt >> 5) & 0x1);
type[4] = ((someInt >> 4) & 0x1);
type[3] = 0;
type[2] = 0;
type[1] = 0;
type[0] = 0;
return type; // 48
}
我只想有数字的第 4 位到 7 位。
多谢!
优雅和最短的方法,只保存一半的字节
可以使用按位 AND 将一半的位设置为零。例如:
unsigned char byte = 0b00110110;
unsigned char mask = (1 << CHAR_BIT / 2) - 1;
unsigned char half = byte & mask;
我只想有数字的第 4 位到 7 位。
同样,将 AND 与位掩码一起使用:
unsigned char byte = 0b00110110;
unsigned char mask = 0b01001000;
unsigned char b_4_7 = byte & mask;
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- EvtExportLogneneneba API正在将远程计算机的事件日志保存到远程PC本身.如何将其保存到主机
- 在C++中将类(带有Vector成员)保存为二进制文件
- C++.我想将更改后的特定字符行保存在字符串中
- 使用FFMPEG将RGB图像序列保存到.mp4时出现问题
- 将RGB图像保存为PPM格式
- 哈希文件递归并保存到矢量Cryptopp中
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- 无法通过头文件保存变量的值
- 我们可以将数据永久保存为数据结构吗?
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- 保存/加载大量短数组到二进制文件
- Gstreamer:每 5 秒使用多文件墨水保存图像/jpeg
- 如何访问由共享指针保存的类方法?
- 为什么签名字符可以保存大于 127 的值?
- 优雅和最短的方法,只保存一半的字节