packing and unpacking bits

This is a discussion on packing and unpacking bits within the C Programming forums, part of the General Programming Boards category; I've been reading on how you can compress the actual bits in a program. Below is my code. I've pieced ...

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    13

    packing and unpacking bits

    I've been reading on how you can compress the actual bits in a program. Below is my code. I've pieced it together, but all that I'm getting is the full 8 bits. My output reads like:

    abcd= 01100001 01100010 01100011 01100100

    and I was wanting/hoping it would show just the last 4 bits. Am I way off? What about if I was wanting to try numbers instead of letters? I just don't want to be barking up the wrong tree totally ya know? Don't laugh please. Anyway, below is my code for the output above. Any help or suggestions would be greatly appreciated. thanks!

    #include <limits.h>
    #include <stdio.h>


    void bit_print(int a)
    {
    int i;
    int n = sizeof(int) * CHAR_BIT;
    int mask = 1 << (n-1);
    for (i=1; i<=n; ++i)
    {
    putchar(((a&mask)==0) ? '0':'1');
    a <<=1;
    if (i % CHAR_BIT==0 && i < n)
    putchar(' ');
    }
    }

    int pack(char a, char b, char c, char d)
    {
    int p = a;
    p = (p<<CHAR_BIT)|b;
    p = (p<<CHAR_BIT)|c;
    p = (p<<CHAR_BIT)|d;
    return p;
    }

    int main()
    {
    printf("abcd= ");
    bit_print(pack('a','b','c','d'));
    putchar("\n");
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    > for (i=1; i<=n; ++i)

    If you want to only show the last four, don't start your loop at 1.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21