Linux API读/写和c++;位组 如何使用C++的BITSET容器使用Linux API读写函数?
大概是这样的:Linux API读/写和c++;位组 如何使用C++的BITSET容器使用Linux API读写函数?,c++,linux,serialization,std-bitset,C++,Linux,Serialization,Std Bitset,大概是这样的: #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 //
#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;
}
#包括
#包括
#include//Linux-API-open
#包括//Linux API读、写、关闭
使用名称空间std;
int main(){
//某些设备的某些8位寄存器
//使用矢量进行读写操作。
//使用位集操作单个位。
矢量控制寄存器;
//将控制寄存器的第1位设置为1(真)。
控制寄存器[0]。设置(1);
//打开新文件进行写入(创建文件)
int-fd=0;
const char*path=“./test.txt”;
fd=(开放(路径,O|u WRONLY | O|u CREAT | O|u TRUNC,S|u IRWXU));
//从vector写入文件(使用Linux API)
写入(fd,control_register.data(),control_register.size());
//关闭文件
关闭(fd);
返回0;
}
我们可以不使用向量容器立即写入位集吗?您可以做的是,在写入数据之前转换为
std::bitset
。差不多
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);
std::位集控制寄存器=0b00101100;//使用一些常量并组合它们
//使用按位或(|)使其更
//可读
uint8\u t ctrl=static\u cast(controlRegister.to\u ulong()&0xFF);
写入(fd和ctrl,1);
不可能用std::vector
等效地代替std::vector
std::bitset
是它自己的类,与uint8\u t
不同,这只是(可能的)基础类型。在调用read
和write
之前,问题就已经开始了<代码>控制寄存器[0]。设置(1)是错误的,因为索引0
->中没有未定义行为的元素为什么不将其转换为char
并写入<代码>位集有到字符串
和到长
方法可以帮助您。供参考:谢谢。我知道这种可能性。但我决定问问,以防有其他选择。