首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MSB与LSB相结合

MSB与LSB相结合
EN

Stack Overflow用户
提问于 2015-04-21 15:11:34
回答 3查看 2.2K关注 0票数 1

我有一个返回1 Byte的函数

代码语言:javascript
复制
uint8_t fun();

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

代码语言:javascript
复制
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]));

是这样吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-04-21 15:21:49

最好自己显式地将8位值加入到16位值中:

代码语言:javascript
复制
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);

顺便说一句,上面的假设是很少的。

票数 2
EN

Stack Overflow用户

发布于 2015-04-21 15:37:54

你会遇到对齐问题。任何指向短时的指针都可以被看作是指向字符的指针,但是在非8位机器上,逆不能保证。

国际水文学组织,这将更安全:

代码语言:javascript
复制
struct {
    char arr0;
    union {
        char array[8];
        uint16_t sarr[4];
    } u;
} s;

s.arr0 = fun();
for ( i = 0; i< 8 ; i++){
    s.u.array[i] = fun();
}

printf( " 1. Byte %x  a = %d , b=%d c =%d d=%d\n" ,
    s.arr0,   
            s.u.sarr[0],
            s.u.sarr[1],
            s.u.sarr[2],
            s.u.sarr[3]);

但是我想您应该正确地处理机器上的endianness,并且知道如何转换2字符<=> 1的简短工作.

票数 1
EN

Stack Overflow用户

发布于 2015-04-21 15:42:30

尝试使用struct来安排数据和移位操作以转换为异能。

代码语言:javascript
复制
// The existence of this function is assumed from the question.
extern unsigned char fun(void);

typedef struct
{
    unsigned char Byte;
    short WordA;
    short WordB;
    short WordC;
    short WordD;
}   converted_data;

void ConvertByteArray(converted_data* Dest, unsigned char* Source)
{
    Dest->Byte = Source[0];
    // The following assume that the Source bytes are MSB first.
    // If they are LSB first, you will need to swap the indeces.
    Dest->WordA = (((short)Source[1]) << 8) + Source[2];
    Dest->WordB = (((short)Source[3]) << 8) + Source[4];
    Dest->WordC = (((short)Source[5]) << 8) + Source[6];
    Dest->WordD = (((hshort)Source[7]) << 8) + Source[8];
}

int main(void)
{
    unsigned char array[9];
    converted_data convertedData;

    // Fill the array as per the question.    
    int i;
    for ( i = 0; i< 9 ; i++)
    {
        array[i] = fun();
    }

    // Perform the conversion
    ConvertByteArray(&convertedData, array);

    // Note the use of %h not %d to specify a short in the printf!
    printf( " 1. Byte %x  a = %h , b=%h c =%h d =%h\n",
        (int)convertedData.Byte,  // Cast as int because %x assumes an int.
        convertedData.WordA,
        convertedData.WordB,
        convertedData.WordC,
        convertedData.WordD );

   return 0;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29776235

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档