Simple Binary Conversion

I’d like to take a 3-bit binary message and convert it to an integer.

I came up with the following way of doing things - but I’d like to believe there’s something simpler.
Is there a convenience class or something that I am missing?

Thanks.

n = [];
x = 111;
x = x.asString;
x.do{|m|
	n = n.add(m.digit);
};
n.convertDigits(2);

Not entirely clear what you try to accomplish since neither 111 nor “111” in itself are a “3-bit binary message” but here is how you could notate a binary number directly in supercollider: 2r111

From my work with bytebeats I came up with this conclusion: Conversion between Integers and Arrays of 0/1 Integers is straightforward, conversion between Integers and 0/1 Strings is not quite. However, you can always make a little helper Function. Also, might well be that there exists something even simpler.


// conversion from and to Array of 0/1 Integers
a = 19.asDigits(2);
a.convertDigits(2);

// conversion from and to 0/1 Strings
// the hurdle here is the less obvious conversion from String to Array
b = 19.asDigits(2).join;
b.as(Array).collect(_.digit).convertDigits(2);

// or, more lengthy
b.sum { |x, i| 2 ** (b.size - 1 - i) * x.digit }.asInteger;

For conversion from int to binary these are probably easier:

7.asBinaryDigits; // [ 0, 0, 0, 0, 0, 1, 1, 1 ]
7.asBinaryString; // "00000111"

round-trip conversion

7.asBinaryDigits.convertDigits(2);
1 Like

Ah, overlooked that, good to know !