c++ - Linux API 读/写和 c++ 位集
问题描述
如何使用具有 Linux API 读/写功能的 C++ 位集容器?
像这样的东西:
#include <vector>
#include <bitset>
#include <fcntl.h> // Linux API open
#include <unistd.h> // Linux API read,write,close
using namespace std;
int main() {
// Some 8-bit register of some device
// Using vector for read and write operations.
// Using bitset to manipulate individual bits.
vector<bitset<8>> control_register;
// Set bit 1 of control_register to 1 (true).
control_register[0].set(1);
// Open new file for writing (create file)
int fd = 0;
const char *path = "./test.txt";
fd = (open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU));
// Write to file from vector (using Linux API)
write(fd, control_register.data(), control_register.size());
// close file
close(fd);
return 0;
}
我们可以不使用向量容器而立即编写位集吗?
解决方案
您可以做的是,std::bitset
在写入数据之前转换为 a 。就像是
std::bitset<8> controlRegister = 0b00101100; // Use some consts and combine them
// with bitwise or (|) to make this more
// human readable
uint8_t ctrl = static_cast<uint8_t>(controlRegister.to_ulong() & 0xFF);
write(fd, &ctrl , 1);
推荐阅读
- c++ - 在 ubuntu 中使用 sln 文件编译 c++ 项目
- python - 图像映射到参考形状 OpenCv
- powershell - 检查文件是否存在,然后移动它
- c# - 如何使用 RhinoETL 框架读取 SQL Server 表?
- python - 如何在 Python 中获取 FIrebase 数据库结果的第一项?
- powershell - 将文件复制到文件夹和所有子文件夹中
- python - 我正在尝试从多个进程写入同一文件并出现错误
- python - 打印到标准输出会给出正确的列表,但附加到列表不会
- php - Laravel 5.6 ajax 没有表单的帖子
- redux - Redux 是 Model-View-ViewModel 的一个实例吗?