繁体   English   中英

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

[英]store three bits value to unsigned char array

我正在尝试采用给定的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;    

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

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM