简而言之结合 MSB 和 LSB

标签 c

我有一个函数返回 1 Byte

uint8_t fun();

该函数应该运行 9 次,所以我得到 9 字节 我想将最后一个 8 作为 4 short values 这里我所做的,但是我'我不确定我得到的值是否正确:

char array[9];
.............

for ( i = 0; i< 9 ; i++){
array[i] = fun();

}

printf( " 1. Byte %x  a = %d , b=%d c =%d \n" ,
    array[0],   
            *(short*)&(array[1]),
            *(short*)&(array[3]),
            *(short*)&(array[5]),
            *(short*)&(array[7]));

是吗?

最佳答案

最好明确一点,自己将 8 位值连接到 16 位值中:

uint8_t  bytes[9];
uint16_t words[4];

words[0] = bytes[1] | (bytes[2] << 8);
words[1] = bytes[3] | (bytes[4] << 8);
words[2] = bytes[5] | (bytes[6] << 8);
words[3] = bytes[7] | (bytes[8] << 8);

顺便说一句,上面假设小端。

关于简而言之结合 MSB 和 LSB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29776235/

相关文章:

c - Pebble watch 开发教程中的点语法是什么意思?

c - 函数不返回数组值

c - 如果地址已知,如何通过指针处理地址内容而不触发段错误?

c++ - Ubuntu 14.04更新gcc 5.1.0报错

c - 使用自相关进行基音检测

c - 如何在c中实现定时器?

c - 使用 setvbuf() 禁用标准输入和标准输出的缓冲

c++ - `/path/to/uthash/utarray.h' 需要 CMake make[2] : *** No rule to make target `HelloTest' , 。停止

c - 如何将 char * 更改为等效的 Go

C 字符数组与字符指针的区别