Forums > Javascript

"crossing the bridge" with bit accuracy from js to max

September 19, 2013 | 2:05 pm

Hello, I’m generating bit patterns via javascript to send over the serial port (via serial object). It seems that max interprets all non-string variables as floats, and so I get rounding errors on the output of the js object. Some of these patterns are headers, so need to be bit accurate. I tried an ArrayBuffer to "cast" to Uint32, which works as long as I’m in javascriptland, but max ignores this, and treats it as a float anyway; I try to force it to an int with:

outlet(0, "int", myOutput);

but this rounds the float on the conversion, and changing the bit pattern.

Any ideas for a work-around?

Christopher Deckard
Seattle, Wa

September 20, 2013 | 5:44 am

You might have more luck with:
outlet(0, Math.round(myOutput));
outlet(0, Math.floor(myOutput));

The problem is just that JavaScript doesn’t have integers, what a wonderful world ;-)

September 20, 2013 | 9:10 am

thanks for the reply, Emmanuel. I didn’t realize javascript didn’t have integers *at all*! So it seems that it’s still possible for the .round() and floor() functions to change the bit pattern. But I did realize a work-around using strings that seems to work. At the output, I do the following:

outlet(0, my32BitPattern[0].toString(10));

I then use a "fromSymbol" object afterwards that then feeds a simple javascript msg_int() fn to break it into bytes to finally feed a "serial" object. Works a treat!


September 20, 2013 | 12:24 pm

Yeah javascript has Numbers ;-)

I would recommend using Math.floor()/Math.round(). toString is going to convert your Number to a string. JavaScript strings are converted to symbols when going on the Max side, and symbol stick there in memory for ever so you don’t want to generate symbols for this.

September 20, 2013 | 1:20 pm

that’s interesting about the memory persistence, Emmanuel. Does Max have any sort of "clear mem" function? Unless I’m missing something, I don’t think floor() or round() will work.

for example, if I load my header bitPattern via:

my32BitPattern[0] = 0xDEADBEEF;

javascript thinks this is -6.259853398707798E18. If I then do a floor() or round(), it will then think it is -7. x 10^18, correct?

wait — I just thought about this a bit more — I simply need to use ArrayBuffer to manipulate javascript to treat the number as an integer, then use the floor() function on the way out to max.

Christopher Deckard,

Viewing 5 posts - 1 through 5 (of 5 total)