Let's say I want to write a function that takes an integer that is 8 bits wide as input, and the function does some manipulation on the bits position and return the value. For example, the input X is 0x35, which is binary 00110101. The output I want it to be is 01010011 -- the higher nibble and lower nibble swap their positions.
unsignedchar swap(unsignedchar byte)
{
// shift lower bits by 4 palces and shift high bits by 4. Then perform bitwise OR
return (byte<<4)|(byte>>4);
}
int main()
{
int x=0x35;
cout <<(int)swap(x);
}
Thanks. It is very helpful. But I am actually looking for more generic answer -- I am converting a piece of Verilog code to C/C++ code. Verilog is similar to C, except it can process individual bits directly.
So let's look at a more generic example. This time the input of the function is a 35-bit long "integer", and the return value is the same type (35 bits integer). The function re-arranges the bit position of the input - for example, input has bit order 0, 1, ... 34, and the output is bit 15,9,3,27... .
stdint.h is not standard C++. VC++, while also being a C compiler, doesn't fully support C99. One of the things it doesn't support is that header.
Just use unsigned char, which is guaranteed to be 8 bits long. Sort of.
VC++ has __int8, __int16, __int32, and __int64 with their unsigned versions as data types, but those aren't portable, either.