首先,您拥有的“已知”值并不是您认为的那样:
#include <stdio.h>
static void p24(int x)
{
printf("%8d = 0x%06X\n", x, (0x00ffffff & (unsigned)x));
}
int main(int argc, char *argv[])
{
p24(-57);
p24(-214528);
p24(-54215);
p24(-1462);
return 0;
}
在 2s 补码机上编译运行打印
-57 = 0xFFFFC7
-214528 = 0xFCBA00
-54215 = 0xFF2C39
-1462 = 0xFFFA4A
当转换为 2s 补码时,您当然必须填充到您正在使用的目标数据类型的全长,以便正确继承符号。然后将有符号数据类型划分为设计的位数。
前任:
#include <stdio.h>
#include <stdint.h>
/* 24 bits big endian */
static char const m57[] = {0xFF, 0xFF, 0xC7};
static char const m214528[] = {0xFC, 0xBA, 0x00};
static char const m54215[] = {0xFF, 0x2C, 0x39};
static char const m1462[] = {0xFF, 0xFA, 0x4A};
static
int32_t i_from_24b(char const *b)
{
return (int32_t)(
(((uint32_t)b[0] << 24) & 0xFF000000)
| (((uint32_t)b[1] << 16) & 0x00FF0000)
| (((uint32_t)b[2] << 8) & 0x0000FF00)
) / 256;
}
int main(int argc, char *argv[])
{
printf("%d\n", i_from_24b(m57) );
printf("%d\n", i_from_24b(m214528) );
printf("%d\n", i_from_24b(m54215) );
printf("%d\n", i_from_24b(m1462) );
return 0;
}
将打印
-57
-214528
-54215
-1462