从 uint16_t 转换到 int16_t

casting and shifting to from uint16_t to int16_t

我有一个关于转换和移动的菜鸟问题。我正在尝试将数组中 uint8_t 的两个元素作为单个带符号元素存储在类型 int16_t 的数组中。但是我的结果不正确,我不知道为什么。

我有这个代码:

uint8_t buffer[BUFFER_SIZE];
int16_t mp3_stereo_buffer[BUFFER_SIZE];

for (i = 0; i < BUFFER_SIZE; i += 2) {
    mp3_stereo_buffer[i] = ((uint16_t)buffer[i] << 8) | ((uint16_t)buffer[i + 1]);
}

首先,可以将Nuint8_t个元素打包成N/2uint16_t个元素。

uint8_t buffer[BUFFER_SIZE];
uint16_t mp3_stereo_buffer[BUFFER_SIZE / 2];

那么你需要知道你的数据是little-endian还是big-endian。

对于little-endian:

for (i = 0; i < BUFFER_SIZE / 2; i++) {
  mp3_stereo_buffer[i] = (uint16_t) (buffer[i*2] | (buffer[i*2+1] << 8));
}

对于big-endian:

for (i = 0; i < BUFFER_SIZE / 2; i++) {
  mp3_stereo_buffer[i] = (uint16_t) ((buffer[i*2] << 8) | buffer[i*2+1]);
}

p.s。如果您的数据实际上已签名,那么您可以将类型和转换更改为 int16_t 但请注意,不保证签名数字的表示方式是可移植的。

#define LITTLE_ENDIAN
int main()
{
uint8_t buffer[4]={0x15,0xff,0x63,0xee};
int16_t mp3_stereo_buffer[2];

for (int i = 0; i < 2; i += 1) {
    mp3_stereo_buffer[i] = ((int16_t*)buffer)[i];

#ifdef LITTLE_ENDIAN
    mp3_stereo_buffer[i]=(mp3_stereo_buffer[i]>>8 &0x00ff) | (mp3_stereo_buffer[i]<<8 & 0xff00);              
#endif

    printf("%x\n",mp3_stereo_buffer[i]&0xffff);
 }
return 0;
}