Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store 8 bits in char using C

Tags:

c

char

binary

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.

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.

like image 994
jhon Avatar asked Jul 20 '10 10:07

jhon


Video Answer


4 Answers

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);
like image 141
UncleZeiv Avatar answered Sep 28 '22 03:09

UncleZeiv


like this....

unsigned char mybyte = 0xF3;
like image 21
Keith Nicholas Avatar answered Sep 28 '22 01:09

Keith Nicholas


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);
}
like image 28
pascal Avatar answered Sep 28 '22 03:09

pascal


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.

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

like image 33
PeterK Avatar answered Sep 28 '22 03:09

PeterK