我有一个 unsigned char 并向它添加整数,但我想获取sizeof
下一个字节(即sizeof
unsigned short int
或unsigned int
等等)。
以下代码演示了我想要的:
#include <stdio.h>
static void write_ushort(unsigned char *b, unsigned short int value) { b[1] = value >> 8; b[0] = value; }
static void write_ulong(unsigned char *b, unsigned long int value) { write_ushort(b + 2, value >> 16); write_ushort(b, value); }
static unsigned short int read_ushort(const unsigned char *b) { return b[1] << 8 | b[0]; }
static unsigned long int read_ulong(const unsigned char *b) { return read_ushort(b + 2) <<16 | read_ushort(b); }
int main() {
unsigned char b[2];
unsigned int v0; /* 4 */
unsigned short int v1; /* 2 */
v0 = 200; v1 = 1235;
write_ushort(&b[0], v0); write_ulong(&b[1], v1);
/* what i expect printf to output is:
* 4 2
* but it obviously outputs 1 1 */
printf("%d %d\n", read_ushort(&b[0]), read_ulong(&b[1]));
printf("%d %d\n", (int)sizeof(b[0]), (int)sizeof(b[1]));
return 0;
}