Writing binary string to file in binary

Okay, I'm working on a Huffman encoding project. Basically I just need to know how to write a string to a binary file. I have a string consisting of all 1s and 0s. I know you can write character in binary format with file.write. However, I already have the binary format that I wish to write. Instead of writing the binary value for the character '1' or '0' I actually want to write that 1 or 0 as binary. Any ideas?

 
string encodedMsg = "1110111111111101001011110110110011000010"; //Example of my string 
one character is one byte (8 bits). You could shove groups of 8 binary digits into one byte. Just do that with bitwise operators.

EDIT: some pseudo code

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

binary_vector<bool>

for every character in encodedMsg {
  binary_vector.push_back((character == '1') ? true : false)
}

bite_vector<uint8_t>

for each group of 8 in binary_vector {
  // One byte
  uint8_t bite;
  for each booleanvalue in the group {
    bite &= booleanvalue << (8 - position)
  }
  bite_vector.push_back(bite)
}

for every byte in bite_vector {
  file.write(byte)
}


NOTE: you CANNOT write a single binary digit by itself. You have to write in groups of 8 (or a byte / word)
Last edited on
Topic archived. No new replies allowed.