0

I tried char a[9]=bitset<8>(f[1]) but as many of you know that did not work. i want to copy the binary value to an array so basically if f[1] will be 'a' the char a will be 01100001

And also , this is not a duplication the question asked before was not what I searched.

Lendrit
  • 19
  • 1
  • 5

1 Answers1

1

You can't direct-initialize an array from an object. You'll need to define the array an then initialize it. Even then, sadly, std::bitset<...> doesn't provide iterators to allow use of std::transform() to fill in the characters. However, a with a simple auxiliary function the initialization can be done:

#include <iostream>
#include <bitset>
template <std::size_t Size>
void initialize(char (&array)[Size], std::bitset<Size - 1> bits) {
    for (std::size_t idx(0); idx != Size - 1; ++idx) {
         array[idx] = '0' + bits[idx];
    }
    array[Size-1] = 0;
}

int main(int, char* av[]) {
    char a[9];
    initialize(a, av[0][0]);
    std::cout << "array=" << a << '\n';
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380