2016-11-17 86 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; 
相關問題