Est-il possible de convertir Bitset <8> en un tableau de caractères d'entiers?
Question
j'ai bitset<8> v8
Et sa valeur est quelque chose comme "11001101", quelque chose en binaire, comment pouvons-nous le convertir en un tableau de caractères ou entiers en C ++?
La solution
Pour convertir en un tableau de char, vous pouvez utiliser le bitset::to_string()
Fonction Pour obtenir la représentation de la chaîne, puis copier les caractères individuels à partir de cette chaîne:
#include <iostream>
#include <algorithm>
#include <string>
#include <bitset>
int main()
{
std::bitset<8> v8 = 0xcd;
std::string v8_str = v8.to_string();
std::cout << "string form: " << v8_str << '\n';
char a[9] = {0};
std::copy(v8_str.begin(), v8_str.end(), a);
// or even strcpy(a, v8_str.c_str());
std::cout << "array form: " << a << '\n';
}
Autres conseils
vector<int> ints;
for(int i = 0 ; i < v8.size() ; i++ )
{
ints.push_back(v8[i]);
}
De même, vous pouvez faire un éventail de caractères. Ou vous pouvez utiliser un tableau brut comme:
char chars[8];
for(int i = 0 ; i < v8.size() ; i++ )
{
chars[i] = v8[i];
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow