我需要2个字节在char pcm[]
转换为1个字节short pcm_[]
。 This后使用C样式转换,起初我在C++程序中尝试了(使用Qt):比特移位`char`与`无符号char`
#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();
}
我想通了,如果我在位移用unsigned char
,但不要认为它只能明白,为什么这是必要的,因为输入是char
。
此外,我想用C++ - 风格放送,并与这一个想出了:
short pcm_3 = (static_cast<unsigned char>(pcm[1])) << 8|
static_cast<unsigned char>(pcm[0]);
qDebug()<<pcm_3;
同样,我需要使用unsigned char
而不是char
。
所以我有2个问题:
- 是
static_cast
正确的投?在我看来,这是一个使用reinterpret_cast
的地方的例子。但是,重新解释演员表不起作用。 - 为什么我必须使用
unsigned char
?
我想你应该转换为'unsigned short'或'unsigned int'。弗拉德来自莫斯科的答案解释了为什么它也可以工作(感谢通常的算术转换)如果投射到'unsigned char',但我觉得这个代码相当混乱。 – 5gon12eder
@TheParamagneticCroissant在这段代码中只有'0x12'被移动,所以他(可能是偶然)回避了那一个 –
另外:如果你想要一个8位类型或者16位类型,你应该使用'uint8_t' /'int8_t'或者'uint16_t' /'int16_t'。除了#2:当你使用位时,你应该总是使用无符号类型,除非你真的了解签名类型的怪癖。 – Hurkyl