[C++] bit shifting[C++] bit shifting

🧑‍🚀

A Human Message

Week 4, 2026

//week4.cpp //instructions: copy line long msg into a file named data.txt (single line, no spaces) //compile with the following //g++ -o week4 week4.cpp //run atcommand line: week4 < data.txt > outfile.txt #include int main(int argc, char * argv[]) { unsigned char byte = 0; int bits = 0; for(;;) { char buffer[1024]; int len = fread(buffer, 1, sizeof(buffer), stdin); // if there was a read error or EOF, stop if (len <= 0) break; for(int i = 0; i < len; ++i) { switch(buffer[i]) { // if a binary 1, turn on bit zero case '1': byte |= 1; break; // if a binary 0, do nothing case '0': break; // if antyhing else, skip default: continue; } // incrment the counter, if we dont yet have 8 bits // shift all the bits left by one if (++bits < 8) byte <<= 1; else { // write out the complete byte fwrite(&byte, 1, 1, stdout); // reset for the next byte bits = 0; byte = 0; } } } // write out any remaining data if the input was not a multiple of 8 in length. if (bits) fwrite(&byte, 1, 1, stdout); return 0; }