jhon
jhon

Reputation: 61

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.

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.

Upvotes: 6

Views: 30001

Answers (5)

UncleZeiv
UncleZeiv

Reputation: 18488

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

Upvotes: 15

pascal
pascal

Reputation: 3365

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

Upvotes: 7

Aamir
Aamir

Reputation: 15576

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

Upvotes: 2

Keith Nicholas
Keith Nicholas

Reputation: 44316

like this....

unsigned char mybyte = 0xF3;

Upvotes: 13

PeterK
PeterK

Reputation: 6317

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

Upvotes: 4

Related Questions