Binary Conversion

There are quite a few ways to convert from decimal to binary or, as I should say, from base ten to base two and the reverse when using Max/MSP. I’ve written abstractions using native objects that provide this function and I’ve also written a javascript that does both conversions (and bases up to 36) in one line of code. It is fairly trivial in javascript using the parseInt() and toString() methods.

Here are two lines of code that can be instantiated via [jstrigger] so you don’t have to load an external javascript file. I haven’t tested them extensively but there are a few things to keep an eye open for: negative numbers cause complaints and anything higher than 1023 in binary will destroy the second object as it can only deal with lists ten items long. They will, however, accept and output numeric lists so nothing needs to be patched through the [fromsymbol] object. You can even change the “2” in each instance to another number up to 9 to change the base you work with. With slight modification this will work all the way up to base 36 as well. I’m sharing them mostly because I like the way the code looks.

jstrigger (a[0].toString(2).split('').map(function(x){return parseInt(x)}))

jstrigger (parseInt(parseInt(a.join().replace('\,'\,''\,'g')\,2).toString(10)))

About these ads

Post a Comment

Required fields are marked *

*
*

Follow

Get every new post delivered to your Inbox.