0

How to use C++ bitset container with Linux API read/write functions?

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?

genpfault
  • 51,148
  • 11
  • 85
  • 139
Blademoon
  • 109
  • 1
  • 8
  • It's not possible to use a `std::vector>` equivalently instead of a `std::vector`. `std::bitset` is it's own class and different from `uint8_t`, that's only the (possibly) underlying type. – πάντα ῥεῖ Sep 28 '20 at 18:39
  • your problems start already before you call `read` and `write`. `control_register[0].set(1);` is wrong because there is no element at index `0` -> undefined behavior – 463035818_is_not_an_ai Sep 28 '20 at 18:45
  • Why not just convert it to `char` and write it? `bitset` has `.to_string` and `.to_ulong` methods that can help you. For reference: https://en.cppreference.com/w/cpp/utility/bitset – Uriya Harpeness Sep 28 '20 at 18:58

1 Answers1

0

What you can do is, to convert to a std::bitset before you write the data. 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);
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190