将三位值存储到无符号字符数组

时间:2019-05-07 10:48:54

标签: c++ c

我试图获取给定的3位值并将3位值存储到unsigned char array [3]中,以下是我的示例,该数组值以二进制显示以便于理解,有人知道吗实现此功能的更好方法?

例如:

unsigned char array[3] = {0};

function_store_3bits_value(3);
array[0] = 011 000 00b
array[1] = 0 000 000 0b;
array[2] = 00 000 000b;

function_store_3bits_value(7);
array[0] = 011 111 00b
array[1] = 0 000 000 0b;
array[2] = 00 000 000b;

function_store_3bits_value(5);
array[0] = 011 111 10b
array[1] = 1 000 000 0b;
array[2] = 00 000 000b;

function_store_3bits_value(2);
array[0] = 011 111 10b
array[1] = 1 010 000 0b;
array[2] = 00 000 000b;

function_store_3bits_value(1);
array[0] = 011 111 10b
array[1] = 1 010 001 0b;
array[2] = 00 000 000b;

function_store_3bits_value(6);
array[0] = 011 111 10b
array[1] = 1 010 001 1b;
array[2] = 10 000 000b;

function_store_3bits_value(7);
array[0] = 011 111 10b
array[1] = 1 010 001 1b;
array[2] = 10 111 000b;    

1 个答案:

答案 0 :(得分:1)

这将使您入门。可能会有各种改进,但这不是“更好的方法”。

unsigned char array[3] = {0};
unsigned int NextBit = 0;   //  Position where the next bit will be written.


#include <limits.h> //  To define CHAR_BIT.


//  Store one bit in the array.
static void StoreOneBit(unsigned x)
{
    //  Limit x to one bit.
    x &= 1;

    //  Calculate which array element the next bit is in.
    unsigned i = NextBit / CHAR_BIT;

    //  Calculate which column the next bit is in.
    unsigned j = CHAR_BIT - (NextBit % CHAR_BIT) - 1;

    //  OR the new bit into the array.  (This will not turn off previous bits.)
    array[i] |= x << j;

    //  Increment position for the next bit.
    ++NextBit;
}


//  Store three bits in the array.
static void function_store_3bits_value(int x)
{
    //  Use unsigned for safety.
    unsigned u = x;

    //  Store each of the three bits.
    StoreOneBit(u>>2);
    StoreOneBit(u>>1);
    StoreOneBit(u>>0);
}


#include <stdio.h>


//  Store three bits and show the result.
static void Do(int x)
{
    function_store_3bits_value(x);
    printf("Stored %d.  Array = %#x, %#x, %#x.\n",
        x, array[0], array[1], array[2]);
}


int main(void)
{
    Do(3);
    Do(7);
    Do(5);
    Do(2);
    Do(1);
    Do(6);
    Do(7);
}