13

Is it possible to detect binary data in JavaScript?

I'd like to be able to detect binary data and convert it to hex for easier readability/debugging.


After more investigation I've realized that detecting binary data is not the right question, because binary data can contain regular characters, and non-printable characters.

Outis's question and answer (/[\x00-\x1F]/) is really the best we can do in an attempt to detect binary characters.

Note: You must remove line feeds and possibly other characters from your ascii string sequence for the check to actually work.

deepwell
  • 20,195
  • 10
  • 33
  • 39

1 Answers1

26

If by "binary", you mean "contains non-printable characters", try:

/[\x00-\x1F]/.test(data)

If whitespace is considered non-binary data, try:

/[\x00-\x08\x0E-\x1F]/.test(data)

If you know the string is either ASCII or binary, use:

/[\x00-\x1F\x80-\xFF]/.test(data)

or:

/[\x00-\x08\x0E-\x1F\x80-\xFF]/.test(data)
outis
  • 75,655
  • 22
  • 151
  • 221
  • I think you mean `regexp.test(data)`. Also, the tab character is printable. โ€“ pimvdb Jul 28 '11 at 15:14
  • "non-printable" in the sense of the [POSIX Locale standard, ยง7.3.1](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap07.html#tag_07_03_01) (which is the basis for the likes of [`isprint`](http://pubs.opengroup.org/onlinepubs/009695399/functions/isprint.html)) as they aren't characters that are printed but rather require the text processor take some special action. You're right in that the OP may want to consider whitespace to be non-binary data. Also, the argument and object for `test` were indeed swapped. โ€“ outis Jul 29 '11 at 01:49
  • 2
    I needed Tab to pass the test, so I'm using `/[\x00-\x09\x0E-\x1F]/` โ€“ Nathan Aug 20 '12 at 21:52