C语言 如何使用C在char中存储8位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3289065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to store 8 bits in char using C
提问by jhon
what i mean is that if i want to store for example 11110011 i want to store it in exactly 1 byte in memory not in array of chars.
我的意思是,如果我想存储例如 11110011,我想将它存储在内存中的 1 个字节中,而不是字符数组中。
example: if i write 10001111 as an input while scanf is used it only get the first 1 and store it in the variable while what i want is to get the whole value into the variable of type char just to consume only one byte of memory.
示例:如果我在使用 scanf 时将 10001111 作为输入写入,它只会获取第一个 1 并将其存储在变量中,而我想要的是将整个值放入 char 类型的变量中,仅消耗一个字节的内存。
回答by UncleZeiv
One way to write that down would be something like this:
写下来的一种方法是这样的:
unsigned char b = 1 << 7 |
1 << 6 |
1 << 5 |
1 << 4 |
0 << 3 |
0 << 2 |
1 << 1 |
1 << 0;
Here's a snippet to read it from a string:
这是从字符串中读取它的片段:
int i;
char num[8] = "11110011";
unsigned char result = 0;
for ( i = 0; i < 8; ++i )
result |= (num[i] == '1') << (7 - i);
回答by Keith Nicholas
like this....
像这样....
unsigned char mybyte = 0xF3;
回答by pascal
Using a "bit field"?
使用“位域”?
#include <stdio.h>
union u {
struct {
int a:1;
int b:1;
int c:1;
int d:1;
int e:1;
int f:1;
int g:1;
int h:1;
};
char ch;
};
int main()
{
union u info;
info.a = 1; // low-bit
info.b = 1;
info.c = 0;
info.d = 0;
info.e = 1;
info.f = 1;
info.g = 1;
info.h = 1; // high-bit
printf("%d %x\n", (int)(unsigned char)info.ch, (int)(unsigned char)info.ch);
}
回答by PeterK
You need to calculate the number and then just store it in a char.
您需要计算该数字,然后将其存储在一个字符中。
If you know how binary works this should be easy for you. I dont know how you have the binary data stored, but if its in a string, you need to go through it and for each 1 add the appropriate power of two to a temp variable (initialized to zero at first). This will yield you the number after you go through the whole array.
如果你知道二进制是如何工作的,这对你来说应该很容易。我不知道你是如何存储二进制数据的,但如果它是一个字符串,你需要遍历它,并为每个 1 添加适当的 2 的幂到临时变量(首先初始化为零)。在您遍历整个数组后,这将为您提供数字。
Look here: http://www.gidnetwork.com/b-44.html
回答by Aamir
Use an unsigned char and then store the value in it. Simple?
使用无符号字符,然后将值存储在其中。简单的?
If you have read it from a file and it is in the form of a string then something like this should work:
如果你从一个文件中读取它并且它是一个字符串的形式,那么这样的事情应该可以工作:
char str[] = "11110011";
unsigned char number = 0;
for(int i=7; i>=0; i--)
{
unsigned char temp = 1;
if (str[i] == '1')
{
temp <<= (7-i);
number |= temp;
}
}

