コンパイル時にサイズがわかる場合は、メソッドもテンプレートにします。そうでない場合は、とにかくstd::vector<bool>
1ビットのみを使用するように実際に特化されたメソッドを使用する必要がありますが、orとビットシフトを使用して手動でビルドする必要があります。bool
ulong
//template version
template <size_t number_of_bits>
string convert_binary_to_hex(string binary_value) {
bitset<number_of_bits> set(binary_value);
ostringstream result;
result << hex << set.to_ulong() << endl;
return result.str();
}
しかし、あなたはすでにulong
ビット数を保持するのに十分な大きさであると想定しているので、そしてあなたが与えたコードに対してビットが多すぎても違いはないので、なぜそれをulong
?_
//reuses ulong assumption
string convert_binary_to_hex(string binary_value) {
bitset<sizeof(ulong)> set(binary_value);
ostringstream result;
result << hex << set.to_ulong() << endl;
return result.str();
}
または、2つの関数を使用することもできます。1つは4ビット数の実際の変換を実行し、もう1つはその関数を使用して任意の長さの数を作成します。
string convert_nibble_to_hex(string binary_value) {
bitset<4> set(binary_value);
ostringstream result;
result << hex << set.to_ulong() << endl;
return result.str();
}
string convert_binary_to_hex(string binary_value) {
//call convert_nibble_to_hex binary_value.length()/4 times
//and concatenate results
}