C++位操作符

位操作是一件比较麻烦的事情;

方法1:

同城就是直接用位操作符;


方法2:

用stl的bitset;

简单了方法,够强大;

可以将 数字 或字符串 初始化设置为二进制, 也可以将二进制 获取为 数字 或 字符串;

如果和 “Bitarray Library” 更强大;


方法3:

可以参考put_bits;


方法4:

从网上找一下比人简单丰封装的函数;但是没有太好的;


方法5:

http://michael.dipperstein.com/bitlibs/

这里的封装比较好;



For some reason I keep finding myself dabbling in the worlds of compression and encryption. I'm not an expert in either of these areas, nor do I aspire to become one. It's just something that catches my interest from time to time.

On computers, both compression and encryption usually take bit patterns with a given meaning and translate them to other patterns intended to have the same meaning. This typically means having to read, write, and manipulate arbitrary groups of bits. To save myself from reinventing the wheel every time I played with another compression or encryption algorithm, I developed two libraries: one for bitwise file reading and writing (bitfile), and the other for manipulating arbitrary length arrays of bits (bitarray).

Some time ago I was asked to modify my LZSS implementation so it could be used on a SEGA Genesis without a file system, so I developed a bitwise array reading and writing library (arraystream). Arraystream is very similar to bitfile, with the major exception being that it operates on arrays.

I originally wrote the bitfile and bitarray libraries in ANSI C, because I used C for my compression algorithms. However, these libraries were one of just a few things that I ever wrote (I've written a lot) where I thought that I could do a better job with C++. So I developed C++ implementations of my bitfile and bitarray libraries. For the time being, the arraystream library is exclusively available in C.

Recently (since 2008 or so) I've been using Python when I've needed quick hacks to do something on a PC (vs an embedded system). After doing some searching of PYPI, the Python Package Index, I noticed there were a number of Python packages that were similar to my bitarray library, but there wasn't anything that provided all the functionality of my bitfile library. I had to fix that problem by providing a pure Python version of my bitfile library too.

I am publishing all of these libraries under the GNU LGPL in hopes that they will be of use to other people.

The rest of this page discusses each of my libraries.

Michael Dipperstein
mdipper@alumni.engr.ucsb.edu


Bitfile Libraries

Implementation

Each version of the bitfile library provides a wrapper around the language's native file I/O. The ANSI C version uses file I/O functions and every bitfile is referenced by a structure which includes a FILE pointer.

The arraystream library uses a similar structure, replacing the FILE pointer with a pointer to an array of unsigned characters and an array index. Arraystream operations are analogous to bitfile operations in almost all respects and will not be discussed further.

The C++ version of the bitfile library makes use of (but does not inherit from) the ifstream and ofstream classes. Every bit file object contains an ifstream pointer and ofstream pointer.

The Python version implements a class containing a Python file object.

In addition to a reference to a native file, each library includes an 8-bit buffer, and counter responsible for tracking the number of bits in the 8-bit buffer. The C and C++ versions of the bitfile library use an unsinged char for the 8-bit buffer.

Reading Bits

Reading bits from a bitfile works as follows:
Step 1. Read a byte from the underlying file and store it in the 8-bit buffer.
Step 2. Set the count of bits in the buffer to 8.
Step 3. Report the least significant bit (lsb) in the buffer as the bit read.
Step 4. Shift the buffer right by one bit.
Step 5. Decrement the count of bits in the buffer.

To read an additional bit, repeat the process from Step 3. Once all bits are read from the 8-bit buffer (the count equals 0) the process starts over from Step 1.

Writing Bits

Writing bits to a bitfile works as follows:
Step 1. Left shift the 8-bit buffer by one bit.
Step 2. Set the least significant bit (lsb) of the 8-bit buffer to the value of the bit being written.
Step 3. Increment the count of bits in the 8-bit buffer.

Repeat the process from Step 1 for each additional bit. Once 8 bits have been written to the 8-bit buffer, the buffer is written to the underlying file and the bit count is set to 0.

I have incorporated some short cuts that bypass the 8-bit buffer in the functions that read/write characters or bytes.

Usage

Rather than writing lengthy man pages for each of the functions in the bitfile library, I have taken a cheap cop-out. The bitfile source includes detailed headers preceding each function. The Python version of the bitfile library includes comments in docstring format.

I have also included a file named sample.[c|cpp|py] which demonstrates the usage of each function in the bitfile library and serves as a test to verify the correctness of the code.

Download

An archive containing the source for each bitfile library may be downloaded by clicking on the links below. My source has been released under the GNU LGPL.

LanguageArchive
ANSI Cbitfile-0.9.ziparraystream-0.2.zip
ISO C++bitfile_cpp-0.8.zip
Pythonbitfile-0.2.tar.gz

Bitarray Library

Implementation

The ANSI C bitarray library provides a collection of functions that create and operate on arrays of bits. The ISO C++ bitarray library provides a class with methods that perform similar functions. Modern versions of the C++ STL providevector<bool> and bitset for similar functionality. My C++ implementation doesn't use the C++ STL.

Bitarrays may be of any size and are implemented as arrays of unsigned char. Bit 0 of the most significant unsigned char(char 0) is the most significant bit (msb) of the bit array. The last (non-spare) bit of the last unsigned char is the least significant bit (lsb).

Example:
An array of 20 bits (0 through 19) with 8 bit unsigned chars requires 3 unsigned chars (0 through 2) to store all the bits.

char012
    
bit 1111111111XXXX
01234567890123456789XXXX

The array data is contained inside a structure/class which includes a count of the number of bits in the array, and a pointer to the memory storing the array. Since arrays may be of arbitrary size, the memory storing the array is dynamically allocated on the heap.

The C++ bitarray class overloads bitwise operators (&, |, ^, ...), providing the expected results on bitarray objects. The C bitarray library provides functions (BitArrayAnd, BitArrayOr, BitArrayXor, ...) for similar functionality.

I have written the bitarray library so that functions and methods requiring multiple bit arrays (such as BitArrayAnd or &), will not do anything if they are given arrays of differing sizes to operate on.

With native arrays, square brackets ([]) may be used to either obtain the value of an array element 1, or to obtain a pointer to an array location 2.

case 1:
if (array[index] == value) ...

case 2:
array[index] = value;

Unfortunately I have not found a way to do anything close to this with bitarrays in C.

In C++ it's not possible to overload square brackets ([]) to behave both ways. Consequently square brackets ([]) returns a bit value and parenthesis (()) returns a class that behaves as a pointer to a bit in the array. The class returned by parenthesis (()) may only be used for assigning bit values.

Usage

A description of each of the functions in my C bitarray library may be found here, unfortunately, I have't written a similar description for the C++ bitarray library. Both the C and C++ bitarray library source archives also include detailed headers preceding each function, and I have included a file named sample.[c|cpp] which demonstrates the usage of each function in the bitarray library.

Portability

All the source code that I have provided is written in strict ANSI C or ISO C++. I would expect it to build correctly on any machine with ANSI C/ISO C++ compilers. I have tested the code compiled with gcc on Linux on an Intel x86 and mingw on Windows XP.

The library includes the routines intended for debugging which dump the array contents to a display. These routines assume that unsigned chars are 8 bits. These routines can easily be written to support any specific size unsigned character. Writing the dump routines to handle arbitrary size unsigned char seems more difficult than it is worth to me. Especially since I only have access to machines with 8 bit unsigned chars.

Download

An archive containing the source for each bitarray library may be downloaded by clicking on the links below. My source has been released under the GNU LGPL.

LanguageArchive
ANSI Cbitarray-0.4.zip
ISO C++bitarray_cpp-0.4.zip

My latest implementations of HuffmanLZSSLZW, and arithmetic encoding all provide additional examples of how to use the C version of these libraries. If you still have any questions or comments feel free to e-mail me atmdipper@alumni.engr.ucsb.edu .





关于位运算在C++中的应用:


一般情况,如果有一个协议,是有几本的位实现的,通常的简单想法是可以在结构体中,用位域的方法实现,如果协议非常好,按字节(8位)可以组成的协议,这样比较简单;

如:

struct stProcl

{

     unsingd char a:5;

     unsing char  b:2;

     unsng char  c:1;

}


但是一般情况位协议就是为了节省空间,节省带宽,所以一般根据协议的具体需要进了减少空间浪费,所以一般的情况可能是:

如:

struct stProcl

{

    unsingd char  a:5;

    unsingd char  b:5;

    unsingd char  c:1;

    unsingd char  d:6;

    unsingd char  e:7;

}

这个情况就比较麻烦,虽然上述是3个字节完成,但是一般在Windows上的字节是“小端模式”,但是位是按照字节(8位)排列的,顺序会不一样,所以这样比较麻烦;

简单来说,“字节“”从右向左,“位”在一个字节中从左向右;

当然如果调整位的排列顺序和协议结构体一样,但是一般不这么做;


所以上述情况一般可以用如下方式表达:

如rtmp的AAC的协议:


struct tagRtmpAAcHead 

std::bitset<4> SoundFormat ;
std::bitset<2> SoundRate;
std::bitset<1> SoundSize;
std::bitset<1> SoundTypeChanl;
std::bitset<8> AACPacketType;

std::bitset<5> AudioObjectType;

std::bitset<4> SampleRateIndex;

std::bitset<4> ChannelConfig;
std::bitset<1> FrameLengthFlag;
std::bitset<1> dependOnCoreCoder;
std::bitset<1> extensionFlag;
}



这样可以通过std::bitse的to_ulong函数获取数值;





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chinabinlang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值