简体   繁体   English

如何使用C在char中存储8位

[英]how to store 8 bits in char using C

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类型的变量中,只消耗一个字节的内存。

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);

像这样....

unsigned char mybyte = 0xF3;

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);
}

You need to calculate the number and then just store it in a char. 您需要计算数字,然后将其存储在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). 我不知道你是如何存储二进制数据的,但如果它是一个字符串,你需要经历它并为每个1添加适当的2的幂来临时变量(首先初始化为零)。 This will yield you the number after you go through the whole array. 这将在您完成整个阵列后产生数字。

Look here: http://www.gidnetwork.com/b-44.html 请看这里: http//www.gidnetwork.com/b-44.html

Use an unsigned char and then store the value in it. 使用unsigned char,然后将值存储在其中。 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM