Thread: Bitmasks and bitwise operators

  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 int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    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.

Popular pages Recent additions subscribe to a feed