2016-11-17 57 views
-2

我是新来存储这种类型的值。我有几个值头字段。 2bit = 2,1bit = 1,1bit = 0,4bit = 13。如何将它存储在uint8中?请帮帮我。如何在一个字节整数中存储2位,1位,1位和4位值

#include <stdio.h> 
#include <stdint.h> 
#include <stdlib.h> 
#include <string.h> 

int main(void) { 
    uint8_t m; 
    uint8_t one, two, three, four; 
    one = 2; 
    two = 1; 
    three = 1; 
    four = 13; 

    // do not know how to store, 

    //assuming m is stored 
    one = (m >> 7) & 1; 
    two = (m >> 5) & 3; 
    three = (m >> 4) & 1; 
    four = m & 15; 
    printf("first %i , second %i, third %i, four %i", one, two, three, four); 
    return 0 
} 
+1

HTTP://www.catb。组织/ ESR /结构包装/ – gj13

回答

0

我觉得这种Bitlayout(memorylayout)会很有用。

typedef struct 
{ 
    UINT32 unOne  : 2; 
    UINT32 unTwo  : 1; 
    UINT32 unThree : 1; 
    UINT32 unFour : 4; 
} MType; 

...

MType  DummyMMsg; 

...

DummyMMsg.unOne = 2; 
DummyMMsg.unTwo = 1; 
DummyMMsg.unThree = 0; 
DummyMMsg.unFour = 13; 
1

看来你已经知道如何使用位移位检索存储的值。反转它以存储值。

m = ((one & 1) << 7) | ((two & 3) << 5) | ((three & 1) << 4) | (four & 15); 

该代码是基于在代码:one是1位,two是2比特,three是1位和four是4位宽。 2分配给one,所以它将被视为零& 1

如果你想2位分配给one和1位two,使用这个存储:

m = ((one & 3) << 6) | ((two & 1) << 5) | ((three & 1) << 4) | (four & 15); 

这对于检索:

one = (m >> 6) & 3; 
two = (m >> 5) & 1; 
three = (m >> 4) & 1; 
four = m & 15; 
相关问题