How to store 8 bits in char using C

I mean, if I want to store, for example, 11110011, I want to store it exactly in 1 byte in memory, and not in an array of characters.

Example: if I write 10001111 as an input, while scanf is used, it only gets the first 1 and stores it in a variable, and what I want is to get the whole value in a variable of type char to consume only one byte memory.

+3
source share
5 answers

One way to write this 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 is a snippet to read it from a line:

int i;
char num[8] = "11110011";
unsigned char result = 0;

for ( i = 0; i < 8; ++i )
    result |= (num[i] == '1') << (7 - i);
+14
source

like this....

unsigned char mybyte = 0xF3;
+10
source

" "?

#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);
}
+6

, char.

, , . , , , , 1 temp ( ). , .

: http://www.gidnetwork.com/b-44.html

+4

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;
    }
}
+1

Source: https://habr.com/ru/post/1755484/


All Articles