views:

4773

answers:

6

I would like to inject binary data into an object in javascript. is there a way to do this?

i.e. var binObj = new BinaryObject('101010100101011');

something to that effect. any help would be great

+9  A: 

You can use parseInt:

var bin = parseInt('10101010', 2);

The second argument (the radix) is the base of the input.

Greg
+1  A: 

Javascript doesn't provide a mechanism to load an object in any form other than simple strings.

Closest you can do is serializing the object to a string, optionally encrypting/compressing it, sending it to the browser, and decrypting/decompressing if necessary, checking for sanity, eval() and pray().

Instead of using eval (which is not quite safe), you can use your own format (alternatively, xml or json for which there are plenty of libs) and parse it yourself.

As a side note, if you want this for obfuscation after the browser gets the usable data (after decrypting/decompressing), it is too easy to circumvent.

artificialidiot
what is the pray() function?
Pim Jager
A: 

What exactly are you trying to load into JavaScript? There are a lot of different alternatives depending on what you need to do.

Dan Herbert
+3  A: 

JavaScript has very little support for raw binary data. In general, it's best to live within this restriction. However, there's a trick I'm considering trying for a project of mine that involves manipulating huge bitmaps to do set operations in an OLAP database. This won't work in IE.

The basic idea is this: coerce the binary data into a PNG to send it to JavaScript, For example, a bitmap might be a black and white PNG, with black being 100% transparent. Then use Canvas operations to do bitwise data manipulation.

The HTML5 Canvas includes a pixel array type, which allows access to bytes in an image. Canvas also supports compositing operations, such as XOR. Lighten and darken should be able to do AND and OR. These operations are likely to be well optimized in any browser that supports them-- probably using the GPU.

If anyone tries this, please let me know how well it works.

David Leppik
When you are using HTML5 canvas, try using processingJS library. They have lots of useful utility functions.
Thej
A: 

above

that is my interest simple ,how to binding image by binary raw data with js

agachart
+5  A: 

There's this binary ajax library that is explained here and there's also another binary parser library that can handle more data types.

You could also look at Google Gears which has a binary Blob object or take a look at making a javascript wrapper for Flash which provides a native ByteArray implementation.

Or... you can sit and wait and hope that all these things become standard :)

RandomEtc