Link to home
Start Free TrialLog in
Avatar of cgoldfarb
cgoldfarb

asked on

Changing a bit value in a binary file

Hi,

I have pulled out my hair trying to figure this out.  I've got the following code which finds a unique number within a bitmap file, and lets the calling method know if the bit representation is turned on or off:

byte valByte;
ifstream readMap (BMP_FILE, ios::in|ios::binary);

if (readMap) {
  // param is a 6-digit number string
  uint16 bitNum = atoi ((char *) &param);
  uint32 byteOffset = bitNum / 8;
  uint16 bitOffset  = bitNum % 8;
  readMap.seekg (byteOffset, ios::beg);
  // Error checking deleted
  readMap.seekg (0, ios::end);
  // Error checking deleted
  readMap.read (&valByte, 1);
  if (valByte & (int)pow (2, bitOffset) && readMap)
    // This bit is turned on
  else
    // This bit is turned off

I now need to be able to flip the bit value.  I was thinking I could try something like this:

if ((valByte & (int)pow (2, bitOffset)) == 0) {
  // If the bit is off, turn it on
  (valByte & (int)pow (2, bitOffset)) = 1;
} else {
  // The card must be on, turn it off
  (valByte & (int)pow (2, bitOffset)) = 0;
};
// Now save the byte back to the file

But for obvious reasons (no Lvalue), this won't work.

For information, this code will only be run on PC-based (8-bit byte based) machines.  Any help would be immensely appreciated!!
Avatar of ozo
ozo
Flag of United States of America image

valByte ^= (1<<bitOffset);
Avatar of faster
faster

ozo means to replace all pow (2, bitOffset) with (1<<bitOffset) and for flip the bit value, use
valByte ^= (1<<bitOffset); this single line does the job of your if/else block.
Avatar of cgoldfarb

ASKER

Thank you both for your help.  It's exactly what I was looking for.  Will hopefully return the favor...
ASKER CERTIFIED SOLUTION
Avatar of erick1217
erick1217

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
255-pow may work better than 256-pow
but it's still pretty silly to use transcendental functions to approximate the << operator
sorry ozo but the power of bit 4 (by example) is 8
and 256 - 8 = 248
valByte &= 248 will set the bit 4 to zero
valByte &= 248 will set bits 0, 1, and 2 to zero
yes.. you're right... excuse me...
erick1217's answer was good, although ozo and faster hit the nail on the head.  They really deserve the points, as they were the first to respond.