Bitmasks and bitwise operators

This is a discussion on Bitmasks and bitwise operators within the C Programming forums, part of the General Programming Boards category; Hey all, I'm working on a project here that needs to read in from an unformatted file and display in ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    18

    Bitmasks and bitwise operators

    Hey all,
    I'm working on a project here that needs to read in from an unformatted file and display in hex, bin, oct, or quart. I've got my binary dump working but I am having trouble with the hex dump. In this blurp of code I'm just trying to store the binary value in an array and then convert to hex, but it only works for the first few bits then prints garbage. Here's what I have so far, thanks!
    Code:
          cmask = 0x000F;
          for(k=1;k<64;k++)
            {
              c = fgetc(finp);
              if((c & cmask) == 0)
                array[count] = 0;
              if((c & cmask) == 1)
                array[count] = 1;
              printf("%d", array[count]);
              count++;
              c >>= 4;
            }
    the k<64 part is just for example, i need to do it for the entire file.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,531
    At the moment, you seem to be getting 1 bit from each character you input.

    Write some functions, so you can do
    c = fgetc(finp);
    showAsBin( c );
    showAsDec( c );
    showAsHex( c );

    Separate the tasks into very specific steps. At the moment, you've got input, binary and hex all (badly) rolled into one loop.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

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