I need to convert 2 bytes in char pcm[]
to a 1 byte short pcm_[]
. This post used a C-style cast, which at first I tried out in my C++ program (using Qt):
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
char pcm[2] = {0xA1, 0x12};
qDebug()<<pcm[0]<<pcm[1];
short pcm_ = ( pcm[1] << 8 )| pcm[0];
qDebug()<<pcm_;
short pcm_2 = ((unsigned char)(pcm[1])) << 8| (unsigned char) pcm[0];
qDebug()<<pcm_2;
return a.exec();
}
I figured out that it only works if I use unsigned char
in the bit shifting, but do not understand, why this is necessary as the input is a char
.
Moreover, I would like to use C++-style-cast, and came up with this one:
short pcm_3 = (static_cast<unsigned char>(pcm[1])) << 8|
static_cast<unsigned char>(pcm[0]);
qDebug()<<pcm_3;
Again, I need to use unsigned char
instead of char
.
So I have 2 questions:
- Is
static_cast
the right cast? In my mind is an example from somewhere that used areinterpret_cast
. However, the reinterpret cast does not work. - Why do I have to use
unsigned char
?