Monday, March 02, 2009

convert



A little bit of C++ that I whipped up to convert to and from binary, since I didn't find anything too inspiring online:


string binary(int v, int bits) {

int p;

string s = "";

for (int i = bits; i >= 0; i--) {
p = pow(2,i);
if (v & (1 << i)) {
s += "1";
} else {
s += "0";
}
}

return s;
}



Convert a bitstream to a floating point number between 0 and 1. It's a smart little function
because it figures out the range from the length of the input string

float convert_bitstring_to_float(string s) {

float v = 0;

int len = s.length();

for (int i = 0; i < len; i++) {
cout << "i=" << i << " s[i]=" << s[i] << endl;
if (s[len-i-1] == '1') {
v += (1 << i);
}
}

return v / (pow(2,len));
}