![](/img/trans.png)
[英]How do I split up a long value (32 bits) into four char variables (8bits) using C?
[英]how to store 8 bits in char using C
我的意思是,如果我想存储例如11110011我想将它存储在内存中的1个字节而不是字符数组中。
例如:如果我在使用scanf时写入10001111作为输入,它只获取第一个1并将其存储在变量中,而我想要的是将整个值放入char类型的变量中,只消耗一个字节的内存。
写下来的一种方法是这样的:
unsigned char b = 1 << 7 |
1 << 6 |
1 << 5 |
1 << 4 |
0 << 3 |
0 << 2 |
1 << 1 |
1 << 0;
这是从字符串中读取它的片段:
int i;
char num[8] = "11110011";
unsigned char result = 0;
for ( i = 0; i < 8; ++i )
result |= (num[i] == '1') << (7 - i);
像这样....
unsigned char mybyte = 0xF3;
使用“位字段”?
#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);
}
您需要计算数字,然后将其存储在char中。
如果您知道二进制如何工作,这对您来说应该很容易。 我不知道你是如何存储二进制数据的,但如果它是一个字符串,你需要经历它并为每个1添加适当的2的幂来临时变量(首先初始化为零)。 这将在您完成整个阵列后产生数字。
请看这里: http : //www.gidnetwork.com/b-44.html
使用unsigned char,然后将值存储在其中。 简单?
如果你从一个文件中读取它并且它是一个字符串的形式,那么这样的东西应该工作:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.