- #1
Jamin2112
- 986
- 12
These are some functions I'm using to encode and decode text.
bitstring returns a string of bits representing the ascii values of the characters in the string passed to the function. For example, passing in "Hi" changes it to "0100100001101001" since (int)'H'=72=01001000 and (int)'i'=105=01101001. The function compress_bitstring takes any sequence of 3 to 9 of the same bits and compresses them by putting the number followed by the bit. For example, "0100100001101001" is changed to "01001401101001". Then the other 2 functions are for undoing the functions I just described.
bitstring returns a string of bits representing the ascii values of the characters in the string passed to the function. For example, passing in "Hi" changes it to "0100100001101001" since (int)'H'=72=01001000 and (int)'i'=105=01101001. The function compress_bitstring takes any sequence of 3 to 9 of the same bits and compresses them by putting the number followed by the bit. For example, "0100100001101001" is changed to "01001401101001". Then the other 2 functions are for undoing the functions I just described.
Code:
#include <iostream>
#include <sstream>
#include <string>
#include <math.h>
static const size_t charbits = 8; // note that sizeof(char) is 1 by the C++ standard
static void bitstring(std::string& str) {
std::string str2(charbits*str.length(), '0');
for (unsigned i = 0; i < str2.length(); i += charbits) {
int this_ascii = (int)str[i/charbits];
for (unsigned j = 0; j < charbits ; j++) { // NOTE: ASCII values are 0-127, 00000000-01111111
if (this_ascii % 2) str2[i+charbits-j-1] = '1';
this_ascii /= 2;
}
}
str = str2;
}
static void undo_bitstring(std::string& str) {
for (unsigned i = 0; i < str.length(); i += charbits) {
int ascii_val = 0;
for (unsigned j = 0; j < charbits; j++) {
if (str[i+j] == '1') ascii_val += (int)exp2(charbits-j-1);
}
str[i/charbits] = (char)ascii_val;
}
str.erase(str.begin()+str.size()/charbits, str.end());
}
static void compress_bitstring(std::string& str) {
std::stringstream ss;
std::string cur_num;
int count = 1;
for (unsigned i = 0; i < str.size()-1; ++i) {
if (str[i] == str[i+1]){
++count;
cur_num = str[i];
if (i == str.size()-2) {
ss << count << cur_num;
} else {
if (count == 9) {
ss << count << cur_num;
count = 0;
}
}
} else if (count > 2) {
ss << count << cur_num;
count = 1;
if (i == str.size()-2) {
ss << str[i+1];
}
} else if (i != str.size()-2) {
for (int j = 0; j < count; ++j) {
ss << str[i];
}
count = 1;
} else {
ss << str[i] << str[i];
}
}
str = ss.str();
}
static void decompress_bitstring(std::string& str) {
unsigned i = 0;
int count;
std::stringstream ss;
while (i < str.size()) {
std::stringstream to_int;
to_int << str[i];
to_int >> count;
if (count > 1){
for (int j = 0; j < count; ++j) {
ss << str[i+1];
}
i = i + 2;
} else {
ss << str[i];
++i;
}
}
str = ss.str();
}