Thread: help with code

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

    help with code

    Please help! I have this, can it be shortened at all? Plus, when it prints out, it prints out the entered data in reverse order, such as 4567 is entered, and 7654 is printed after the bits are printed. Any thoughts to flip this around to show in the correct order? Thanks in advance!


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

    int pack(int, int, int, int);
    int unpack(int, int);
    void bit_print(int);

    int main()
    {
    int i, j, k, l, m, un, pa;
    system("cls");

    printf("Please enter 4 numbers: ");
    printf("\nDo not space between\n");
    scanf("%1d%1d%1d%1d", &i, &j,&k, &l);
    pa = pack(i,j,k,l);
    printf("The numbers you entered are: ");
    printf("%3d%3d%3d%3d\n", i,j,k,l);
    bit_print(pa);
    printf("\n");
    for(m = 0; m < 4; ++m)
    {
    un=unpack(pa, m);
    printf("%d\n", un);
    }
    return 0;
    }

    void bit_print(int e)
    {
    int r;
    int w = sizeof(int) * CHAR_BIT;
    int mask = 1 << (w-1);

    for (r=1; r<=w; ++r)
    {
    putchar(((e&mask)==0) ? '0':'1');
    e <<=1;
    if (r % 4==0 && r < w)
    putchar(' ');
    }
    }

    int pack(int a, int b, int c, int d)
    {

    int p = a;

    p = (p<<4)|a;
    p = (p<<4)|b;
    p = (p<<4)|c;
    p = (p<<4)|d;

    return p;
    }

    int unpack(int x, int z)
    {
    int y = z * 4;
    unsigned mask = 15;

    mask <<= y;
    return ((x & mask) >> y );
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    I find this to be the easiest way to print bits:
    Code:
    void printBits( int b )
    {
        for( x = 0; x < sizeof(int)*8; x++ )
            printf("%c", (b&(1<<x))?'1':'0' );
    }
    If you don't like the order, reverse the loop so that it starts high, and ends low.

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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Extended ASCII Characters in an RTF Control
    By JustMax in forum C Programming
    Replies: 18
    Last Post: 04-03-2009, 08:20 PM
  2. Enforcing Machine Code Restrictions?
    By SMurf in forum Tech Board
    Replies: 21
    Last Post: 03-30-2009, 07:34 AM
  3. Obfuscated Code Contest
    By Stack Overflow in forum Contests Board
    Replies: 51
    Last Post: 01-21-2005, 04:17 PM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. Replies: 0
    Last Post: 02-21-2002, 06:05 PM