Forget bitshifting and unions. Here's a mathematical approach to it. |
Emphasis added.
If you are going to give advice, don't tell newbies to ignore good advice for marginal, harder-to-understand advice.
Forget all the expensive multiplications.
Use bitshifting.
@
SuperSonic
A bitshift just scoots the bits in your value left or right some number. For example, given the value for 0x2B:
00111011
If you bit-shift right one bit (
0x2B >> 1
), the right most bit (a one) gets kicked off the end and the others slide right one space. A zero moves in on the left.
0 -> 0011101 -> 1
00011101
The right bitshift is a very cheap
integer division by two.
The left bitshift is a very cheap
integer multiplication by two.
Since we know that each
byte of your source is exactly eight bits, we can use it to our advantage when assembling integer values that are bigger than eight bits.
The nice trick about bitshifting is:
it doesn't matter how big your integer value is -- as long as you keep shifting bits in, it will work.
Example time:
I want to assemble 0x35 and 0xA1 into an integer. I know that the first byte is the most-significant value, and the second is the least significant. The assembled value should then be 0x35A1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
// Here are our bytes, in order from most-significant to least-significant
unsigned char bytes[] = { 0x35, 0xA1 };
// Here is our value. Start with zero.
int value = 0;
// Loop through the bytes, from most-significant to least-significant, and
// shift them into the value.
for (int n = 0; n < 2; n++)
{
// Here we shift-in the byte
value = value << 8; // scoot all the bits left 8 places
value = value | bytes[ n ]; // set the lower-eight bits to the byte value
// Let's see how it looks right now:
cout << "value = 0x" << setfill( '0' ) << setw( 8 ) << hex << value;
cout << " = " << dec << value << ".\n";
}
return 0;
}
|
Now that you have something to play with, try adding some bytes to the
bytes[] array, and see how it affects the result.
The example I posted earlier shows how to go backwards, and how to deal with different endiannesses. This example used "big-endian", since the more important (significant) bytes were listed first in the array. In "little-endian", the more important (significant) bytes are listed last in the input array.
Hope this helps.