Default User wrote in message news:<3F***************@boeing.com.invalid>...
Here's a way from my personal library:
unsigned int CreateDataWord (unsigned char data[4])
{
unsigned int dataword = 0;
for (int i = 0; i < 4; i++)
{
dataword |= data[i] << (3-i) * 8;
}
return dataword;
}
Note that this uses unsigned char for the buffer, which is guaranteed to
be safe, requires CHAR_BIT == 8, and is predicated on 32-bit int, so it
has its own nonportabilities.
Brian Rodenborn
Thanks for the input, Brian. Regarding your function
CreateDataWord...I just want to point out that if you just want to
pack a char buffer into ints, you can do this portabally while making
no assumptions of the system bit size, or the size of CHAR_BIT.
However, you actually need two functions...depending on how you want
to pack your word...the function you show packs the word Little
Endian. Here is compilable code that uses 2 portable versions of your
function.
#include <iostream>
using namespace std;
void wait();
unsigned int makeBE(unsigned char a[]);
unsigned int makeLE(unsigned char a[]);
bool endian_check();
int main(){
int ws = sizeof(int);
cout << "This is a " << ws * CHAR_BIT << "-bit system\n"
<< "Bytes are " << CHAR_BIT << "-bits\n"
<< "Words are " << ws << " bytes\n\n"
<< "Checking system endianness...System is ";
if(endian_check()) cout << "Little Endian (Intel)\n\n";
else cout << "Big Endian (Motorola)\n\n";
unsigned char data[ws]; // Make a 1-word char array and fill it
for(int i = 0; i < ws; ++i) data[i] = 0x41 + i;
cout << "The " << ws << " byte sequence \"";
for(int i = 0; i < ws; ++i) cout << data[i];
cout << "\" (Ascii)\n"
<< "is translated to a " << ws
<< " byte integer word (hex) as:\n\n" << hex;
cout << "Big Endian(Motorola): " << makeBE(data) << endl;
cout << "Little Endian(Intel): " << makeLE(data) << endl << endl;
wait();
return 0;
}
unsigned int makeBE (unsigned char data[sizeof(int)]){
unsigned int dataword = 0;
for (int i = 0; i < sizeof(int); i++)
dataword |= (data[i] << (i * CHAR_BIT));
return dataword;
}
unsigned int makeLE (unsigned char data[sizeof(int)]){
unsigned int dataword = 0;
int index = 0;
for (int i = sizeof(int); i > 0; )
dataword |= data[index++] << --i * CHAR_BIT;
return dataword;
}
bool endian_check(){
unsigned int word = 0x1;
unsigned char* byte = reinterpret_cast<unsigned char*>(&word);
return (byte[0]); // returns 1 if LE, 0 if BE
}
void wait(){
cout<<"<Enter> to continue..";
string z; getline(cin,z);
}