【问题标题】:Printing bitmap in C在 C 中打印位图
【发布时间】:2023-03-11 02:41:01
【问题描述】:

我正在尝试创建一个包含 100 个 1 和 0 的位图。

下面是我到目前为止出来的内容。我在打印位图时遇到问题,或者我不知道如何打印位图。

我想显示由我设置的所有 1 和 0 组成的位图。对于索引 0 到 99

int main()
{

    unsigned int bit_position, setOrUnsetBit, ch;
    unsigned char bit_Map_array_index, shift_index;

    unsigned char bit_map[100] = { 0 };

    do
    {
        printf("Enter the Bit position (bit starts from 1 and Ends at 100) \n");
        scanf("%d", &bit_position);

        printf(" Do you want to set/unset the Bit (1 or 0) \n");
        scanf("%d", &setOrUnsetBit);


        bit_Map_array_index = (bit_position - 1) / 8;


        shift_index = (bit_position - 1) % 8;

        printf("The bit_position : %d shift Index : %d\n", bit_position, shift_index);

        if (setOrUnsetBit)
        {
            bit_map[bit_Map_array_index] |= 1 << shift_index; //set 1
        }
        else
        {
            bit_map[bit_Map_array_index] &= ~(1 << shift_index); //set 0
        }


        printf(" Do You want to Continue then Enter any Number"
            "and for Exit then enter 100\n");
        scanf("%d", &ch);



    } while (ch != 100);

    //I wan to print bitmap here after exiting

    system("pause");
    return 0;
}

我在 C 编程方面的经验很少......所以无论我错在哪里,请纠正我。

提前致谢。

【问题讨论】:

  • 我想知道你代码中的数字50来自哪里...
  • 修正为8~8bit
  • 试试这个可能有帮助:stackoverflow.com/questions/2525310/…
  • 请发minimal reproducible example,以便我们重现问题。如果没有实际输入、期望输出、实际输出的示例以及缺少关键部分的代码(例如 #include 语句),我们只能猜测实际情况。
  • 编译时,始终启用警告,然后修复这些警告。 (对于gcc,至少使用:-Wall -Wextra -Wconversion -pedantic -std=gnu11

标签: c bitmap bitmapdata


【解决方案1】:

您使用的是字节,而不是位。您有 100 个字节,将每个字节设置为 0 或 1。不需要移位值:

unsigned char bytes[100];
for(int i = 0; i < sizeof(bytes); i++)
    bytes[i] = rand() % 2;

for(int y = 0; y < 10; y++)
{
    for(int x = 0; x < 10; x++)
    {
        int i = y * 10 + x;
        printf("%d ", bytes[i]);
    }
    printf("\n");
}

如果您使用的是位,那么您可以使用

unsigned char data[13];

因为1313 * 8 位或104 位。您只需要100 位。如何设置和获取位取决于您选择的格式。例如,位图文件被填充,因此每行都是 4 字节的倍数。一般来说,您可以将值设置为:

if(bytes[i])
    data[byteindex] |= (1 << shift);
else
    data[byteindex] &= ~(1 << shift);

要取回值:

int value = (data[byte] & shift) > 0;

【讨论】:

猜你喜欢
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多