O'Reilly logo

JavaScript JSON Cookbook by Ray Rischpater

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Encoding and decoding base64 using an ArrayBuffer

If you're going to use ArrayBuffer and DataView for your binary data and carry binary data as base64 strings, you can use the Mozilla-written functions at https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_.232_.E2.80.93_rewriting_atob%28%29_and_btoa%28%29_using_TypedArrays_and_UTF-8 to do so. They provide the functions strToUTF8Arr and UTF8ArrToStr to perform UTF-8 encoding and decoding, as well as base64EncArr and base64DecToArr to convert between base64 strings and array buffers.

How to do it…

Here's an interconversion example that encodes a text string as UTF-8, then converts the text into base64, then shows the base64 results, and finally converts ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required