【问题标题】:store three bits value to unsigned char array将三位值存储到无符号字符数组
【发布时间】:2019-05-07 10:48:54
【问题描述】:

我正在尝试取一个给定的 3 位值并将 3 位值存储到 unsigned char 数组 [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;    

【问题讨论】:

  • “更好的方式”表示你已经实现了这个功能的一个版本——请贴出来。
  • 除非您有非常严格的内存使用要求,否则我不会费心用完所有位。我只会将一个或两个三位值放在单个字符中(也许 wchar 中有 5 个三位值,所以你只浪费 1 位用于填充)。这样您就不必费心打破多个字节之间的值。
  • 还要注意,如果您将这个 3 字节数组与任何其他对象打包在一起,则该对象可能会被填充以适应它需要的对齐方式,从而浪费至少 1 个字节。当然,如果这 3 个字节构成更大的 3 位计数器数组的一部分,那么这不是问题。
  • 如果你真的想把一些小的计数打包成一个整数,看看旧的 c 位字段结构特性。 en.cppreference.com/w/cpp/language/bit_field
  • C还是C++,请下定决心,答案会不一样

标签: c++ c


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 2017-11-27
    • 1970-01-01
    相关资源
    最近更新 更多