c - 在 C 中打印位图

标签 c bitmap bitmapdata

我正在尝试创建 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 编程方面的经验很少...如果我错了,请指正。

提前致谢。

最佳答案

您使用的是字节,而不是位。你有 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;

关于c - 在 C 中打印位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220677/

相关文章:

c++ - C++中分配内存和指针的问题

c - 如何使用 C 获取 Unix 文件的所有者

android 将 XML View 转换为位图而不显示它

c# - Bitmap.LockBits 和 Graphics.FromImage 在 C# 中是否可以组合

python - 如何做简单、可靠的网络消息传递?

c - Eclipse CDT 和未知标签

c++ - wxStaticBitmap构造函数使用wxGDIImage而不是wxBitmap

winapi - HBITMAP 到 BITMAP 的转换

flash - 如何从 BitmapData 中剪切出 Shape?

apache-flex - 逐个比较 AS3 像素中的位图数据