Converting 2 chars (bytes) to a short
From
Nightfox to
All on Thu Jun 2 09:18:56 2011
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..
Nightfox