如何用二进制数组控制相应位置用"printf"打印一些图案?
How to use binary array control the corresponding location to use "printf" to print some patterms?
我发现这个问题:
How to print M character with heart symbols in C language?
一个答案是使用二进制数组来设置需要打印的位置。
char letter_s[7] = {
0b11111111,
0b10000000,
0b10000000,
0b11111111,
0b00000001,
0b00000001,
0b11111111 };
char letter_m[7] = {
0b10000010,
0b11000110,
0b10101010,
0b10010010,
0b10000010,
0b10000010,
0b10000010 };
//and then write code to print '' for every 1 bit in a character array.
像这样打印图案:
♥♥♥♥♥♥♥♥♥
♥
♥
♥♥♥♥♥♥♥♥♥
♥
♥
♥♥♥♥♥♥♥♥♥
我尝试实现这个,使用
char letter_s[1] = {0b11111111};
printf("%d", letter_s[0][0]);
但是我达不到位的水平。所以我想知道如何使用 1 和 0 来控制是否输入。
初学C语言,不知道C语言知识体系的哪一部分可以找到答案,是不是有点折腾?我用的是C Premier Plus的书,看了这一章还是没看懂
如果要访问 char 变量的各个位,则需要使用按位运算符。
在您的示例中,您需要使用按位与运算符,表示为 &,以及可选的左移运算符,表示为 << .
下面是一个示例,它将打印出 char 变量的每一位,从最低有效位到最高有效位:
char c = 0b10101010;
for (int i = 0; i < 8; ++i) {
int bit = (c & (1 << i)) != 0;
printf("Bit %d: %d\n", i, bit);
}
将打印出:
Bit 0: 0
Bit 1: 1
Bit 2: 0
Bit 3: 1
Bit 4: 0
Bit 5: 1
Bit 6: 0
Bit 7: 1
我发现这个问题: How to print M character with heart symbols in C language? 一个答案是使用二进制数组来设置需要打印的位置。
char letter_s[7] = {
0b11111111,
0b10000000,
0b10000000,
0b11111111,
0b00000001,
0b00000001,
0b11111111 };
char letter_m[7] = {
0b10000010,
0b11000110,
0b10101010,
0b10010010,
0b10000010,
0b10000010,
0b10000010 };
//and then write code to print '' for every 1 bit in a character array.
像这样打印图案:
♥♥♥♥♥♥♥♥♥
♥
♥
♥♥♥♥♥♥♥♥♥
♥
♥
♥♥♥♥♥♥♥♥♥
我尝试实现这个,使用
char letter_s[1] = {0b11111111};
printf("%d", letter_s[0][0]);
但是我达不到位的水平。所以我想知道如何使用 1 和 0 来控制是否输入。 初学C语言,不知道C语言知识体系的哪一部分可以找到答案,是不是有点折腾?我用的是C Premier Plus的书,看了这一章还是没看懂
如果要访问 char 变量的各个位,则需要使用按位运算符。
在您的示例中,您需要使用按位与运算符,表示为 &,以及可选的左移运算符,表示为 << .
下面是一个示例,它将打印出 char 变量的每一位,从最低有效位到最高有效位:
char c = 0b10101010;
for (int i = 0; i < 8; ++i) {
int bit = (c & (1 << i)) != 0;
printf("Bit %d: %d\n", i, bit);
}
将打印出:
Bit 0: 0
Bit 1: 1
Bit 2: 0
Bit 3: 1
Bit 4: 0
Bit 5: 1
Bit 6: 0
Bit 7: 1