[英]Linux API read/write and c++ bitset
How to use C++ bitset container with Linux API read/write functions?如何将 C++ bitset 容器与 Linux API 读/写功能一起使用?
Something like this:像这样的东西:
#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;
}
Can we write a bitset right away, without using a vector container?我们可以在不使用矢量容器的情况下立即编写位集吗?
What you can do is, to convert to a std::bitset
before you write the data.您可以做的是在写入数据之前转换为std::bitset
。 Something like就像是
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.