按位读取 结果存入Vector
template< class _Type >
void ReadBit( _Type &_src, vector< int > &_vdest ) {
_vdest.clear();
char *p = ( char * )&_src;
for( int i = sizeof( _src ) - 1; i >= 0; i-- ) {
for( int j = 7; j >= 0; j-- ) {
if( ( *( p + i ) & ( 1 << j ) ) == ( 1 << j ) ) {
_vdest.push_back( 1 );
} else {
_vdest.push_back( 0 );
}
}
}
}
设置某个二进制位
template< class _Type >
bool SetBit( _Type &_src, int _bit_idx, bool _bit ) {
if( _bit_idx > sizeof( _src ) * 8 ) {
//不属于你的数据不能瞎搞。
return false;
}
char *p = ( char * )&_src + ( _bit_idx - 1 ) / 8;
if( _bit ) {
*p = *p | ( 1 << ( ( _bit_idx - 1 ) % 8 ) );
} else {
*p = *p & ~( 1 << ( ( _bit_idx - 1 ) % 8 ) );
}
return true;
}
电脑上数据存在内存中的方式和人直观的方式是相反的。人的感官高位在前低位在后 电脑则是低位在前高位在后 so倒过来读才符合人的感官。
完整程序 测试下函数结果
#include <iostream>
#include <vector>
using namespace std;
//从高到低顺序按位取值 存入vector
template< class _Type >
void ReadBit( _Type &_src, vector< int > &_vdest ) {
_vdest.clear();
char *p = ( char * )&_src;
for( int i = sizeof( _src ) - 1; i >= 0; i-- ) {
for( int j = 7; j >= 0; j-- ) {
if( ( *( p + i ) & ( 1 << j ) ) == ( 1 << j ) ) {
_vdest.push_back( 1 );
} else {
_vdest.push_back( 0 );
}
}
}
}
//设置数据位 _bit_idx 从1开始
template< class _Type >
bool SetBit( _Type &_src, int _bit_idx, bool _bit ) {
if( _bit_idx > sizeof( _src ) * 8 ) {
return false;
}
char *p = ( char * )&_src + ( _bit_idx - 1 ) / 8;
if( _bit ) {
*p = *p | ( 1 << ( ( _bit_idx - 1 ) % 8 ) );
} else {
*p = *p & ~( 1 << ( ( _bit_idx - 1 ) % 8 ) );
}
return true;
}
union Myi16 {
struct {
char LowByte;
char HighByte;
};
short _Short;
};
union MyI32 {
struct {
Myi16 Low16;
Myi16 High16;
};
int i32;
};
union MyI64 {
struct {
MyI32 Low32;
MyI32 High32;
};
_int64 i64;
};
//测试
vector< int > vret;
void vprint() {
for( unsigned int i = 0; i < vret.size(); i++ ) {
cout << vret[ i ];
if( ( i + 1 ) % 4 == 0 ) cout << " ";
}
cout << endl;
}
int main()
{
//C++ 基础类型int测试
int n = 0;
cout << "初始值全0:" << endl;
ReadBit( n, vret );
vprint();
cout << "第8位设置成1:" << endl;
SetBit( n, 8, true );
ReadBit( n, vret );
vprint();
cout << endl;
n = 0xFFFFFFFF;
cout << "初始值全1:" << endl;
ReadBit( n, vret );
vprint();
cout << "第8位设置成0:" << endl;
SetBit( n, 8, false );
ReadBit( n, vret );
vprint();
cout << endl;
//搞个结构试试
MyI64 i64;
i64.i64 = 0;
cout << "初始值全0:" << endl;
ReadBit( i64, vret );
vprint();
cout << "第30位设置成1:" << endl;
SetBit(i64, 30, true );
ReadBit( i64, vret );
vprint();
cout << endl;
i64.i64 = 0xFFFFFFFFFFFFFFFF;
cout << "初始值全1:" << endl;
ReadBit( i64, vret );
vprint();
cout << "第32位设置成0:" << endl;
SetBit( i64, 32, false );
ReadBit( i64, vret );
vprint();
cout << endl;
system( "pause" );
return 0;
}
运行结果

OK!!