In C or C++, suppose there is an array of 2 chars:
char charArray[2];
If one wanted to convert those 2 char values to a short, I can think of 2 ways to do it:
- Method 1 - Bit shifting and ORing:
short shortVal = ((charArray[1] << 8) | charArray[0]);
- Another way I've tried this:
short shortVal = (short)(charArray[1]);
shortVal <<= 8;
shortVal |= charArray[0];
- Method 2 - Using memcpy():
short shortVal = 0;
memcpy((void*)&shortVal, (void*)charArray, 2);
Is either way any better than the other? And does the bit-shift & OR
method look fine? I'm asking because I'm working on some C++ code for reading & writing WAV files, and when using the bit-shift/OR method to read 16-bit audio samples, the audio sounds a bit distorted, but using the memcpy() method, it sounds fine. I'm not sure why that is, unless I'm not bit-shifting or ORing correctly in the first method..
The first way is the correct way if the charArray is big endian. The second method (memcpy) is architecture dependant and will not work on big-endian platforms. I think what you meant to do was:
short shortVal = ((charArray[0] << 8) | charArray[1]);
Sysop: | Eric Oulashin |
---|---|
Location: | Beaverton, Oregon, USA |
Users: | 94 |
Nodes: | 16 (0 / 16) |
Uptime: | 09:50:55 |
Calls: | 5,138 |
Calls today: | 5 |
Files: | 8,491 |
D/L today: |
1 files (279K bytes) |
Messages: | 352,562 |