如何在一个字节整数中存储2位,1位,1位和4位值

时间:2016-11-17 12:40:53

标签: c

我是存储此类值的新手。我对标题字段的值很少。 2bit = 2,1bit = 1,1比特= 0,4比特= 13.我如何按顺序将它存储在uint8中?请帮帮我。

#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
} 

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;