私のゲーム用のデータパッカーを作成しています。アイデアは、属性をパックし、ネットワーク上やデータパッキングが望ましい他の領域にデータを流すことができるものを書くことです。私はhttp://cplusplus.com/articles/zb07M4Gy/のバージョンを使って私の目標の一部を達成しました。私のコードは次のようになります:C++で移動せずにユニオンからビットにアクセスする
namespace detail
{
// Determine whether _Type is signed or unsigned.
// _Result is then either a signed or unsigned char
template < typename _Type >
struct sign
{
typedef typename std::_If< std::tr1::is_unsigned<_Type>::value, unsigned char, signed char >::_Type _Result;
};
}
// Template for packing and unpacking data
// at bit and byte level
template < typename _Type >
struct packer
{
typedef typename _Type value_type;
static const int num_bytes = sizeof(value_type);
static const int num_bits = num_bytes * CHAR_BIT;
union
{
value_type packed_value;
typename detail::sign<value_type>::_Result byte[num_bytes];
};
};
ビットシフトなしで個々のビットへのアクセスを許可するにはどうすればよいですか?私はstd :: bitsetを使うことはできません。なぜなら、それは普通のコンストラクタを持っていて、boolの配列はビットの代わりに各エントリにバイトを割り当てる結果になるからです。
理想的には、ビット設定/マクロのチェックを避けたいと思います(ただし、私の手は縛られているようですが)。移植性とエンディアンの問題がありますが、それを除いて、私の目標を達成する方法はありますか?再帰的に配列を建設する
template< int _NumBits >
struct bit_field
{
bit_field< _NumBits - 1 > the_other_bits;
int value : 1;
int operator[](const int in_index)
{
return reinterpret_cast< int* >(this)[index];
}
};
template< >
struct bit_field<0>
{
int value : 1;
int operator[](const int in_index)
{
return reinterpret_cast< int* >(this)[index];
}
};
:
私が持っていたアイデアのようなものを使用することでした。しかし、この構造体の問題は整列です。この構造体はMSVC10の4バイトでパッカー構造体に132バイトの合計を与えます。これは4バイトの整数で作業する場合には理想的ではありません...
提案(「マン・アップ・ビットシフト」を含む...)は大歓迎です。
+1「ビットシフトを使用しない」ソリューションを提供するため。 –
私はこの道を下ることを非常に誘惑しています。私は、8ビット以外の数字であるシステムで作業するつもりはないと確信しているので、8ビットバイトが安全であると仮定します。また、ビットシフトを使用しない答えを提供するために1つプラス。 – BigDaveDev