Javascript array buffer to string

10 examples of ‘arraybuffer to string’ in JavaScript

Every line of ‘arraybuffer to string’ code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

7function arrayBufferToString(arrayBuffer)
8 const byteArray = new Uint8Array(arrayBuffer);
9 const strArr = [];
10 for (let i = 0; i < byteArray.length; ++i)
11 strArr[i] = String.fromCharCode(byteArray[i]);
12 >
13 return strArr.join('');
14>
182function arrayBufferToString(arrayBuffer)
183 var byteArray = new Uint8Array(arrayBuffer);
184 var byteString = '';
185 for (var i = 0; i < byteArray.byteLength; i++)
186 byteString += String.fromCharCode(byteArray[i]);
187 >
188 return byteString;
189>
3function ArrayBuffer2string (ar)
4 var i, res, ar8;
5
6 ar8 = new Uint8Array(ar);
7 res = '';
8
9 for (i = 0; i < ar8.length; i++)
10 res += String.fromCharCode(ar8[i]);
11 >
12
13 return res;
14>
25function base64ArrayBuffer(arrayBuffer)
26 var base64 = ''
27 var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
28
29 var bytes = new Uint8Array(arrayBuffer)
30 var byteLength = bytes.byteLength
31 var byteRemainder = byteLength % 3
32 var mainLength = byteLength - byteRemainder
33
34 var a, b, c, d
35 var chunk
36
37 for (var i = 0; i < mainLength; i = i + 3)
38 chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
39
40 a = (chunk & 16515072) >> 18
41 b = (chunk & 258048) >> 12
42 c = (chunk & 4032) >> 6
43 d = chunk & 63
44
45 base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
46 >
47
48 if (byteRemainder == 1)
49 chunk = bytes[mainLength]
50
51 a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
52 b = (chunk & 3) << 4 // 3 = 2^2 - 1
53 base64 += encodings[a] + encodings[b] + '=='
54 > else if (byteRemainder == 2)
55 chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
56
57 a = (chunk & 64512) >> 10
58 b = (chunk & 1008) >> 4
59 c = (chunk & 15) << 2
60 base64 += encodings[a] + encodings[b] + encodings[c] + '='
61 >
62
63 return base64
64>
75function typedArrayToString(buffer)
76 var string = '';
77 for (var i = 0; i < buffer.length; i+= 100)
78 string += String.fromCharCode.apply(undefined, buffer.subarray(i, i + 100));
79 return string;
80>
52static arrayBufferToString(arrayBuffer)
53 if (typeof TextDecoder !== 'undefined')
54 let textDecoder = new TextDecoder();
55 return textDecoder.decode(arrayBuffer);
56 > else
57 let bytes = new Uint8Array(arrayBuffer);
58 let result = "";
59 let length = bytes.length;
60 for (let i = 0; i < length; i++)
61 result += String.fromCharCode(bytes[i]);
62 >
63 return result;
64 >
65>
2function arrayBufferToBase64(buffer)
3 return buffer.toString('binary');
4>
72export function buffer2string(buffer)
73 const array = new window.Uint8Array(buffer);
74 const sliceSize = 8192;
75 const slices = [];
76 for (let i = 0; i < array.length; i += sliceSize)
77 slices.push(String.fromCharCode.apply(null, array.subarray(i, i + sliceSize)));
78 >
79 return slices.join('');
80>
7function stringToArrayBuffer(str)
8 var buf = new ArrayBuffer(str.length * 2);
9 var view = new Uint16Array(buf);
10 for (var i = 0, c = str.length; i < c; i++)
11
12 view[i] = str.charCodeAt(i);
13 >
14 return buf;
15>
67var arrayBufferToString = function arrayBufferToStringArray(buf)
68 return String.fromCharCode.apply(String, arrayBufferToNumberArray(buf))
69 .replace('\0', '\u2400');
70>;
  1. jquery array to string
  2. readasarraybuffer
  3. json string to array
  4. jquery split string to array
  5. jquery to string
  6. jquery tostring
  7. mongoose array of strings
  8. js array to string without commas
  9. jquery convert to string
  10. remove string from array
  11. jquery int to string
  12. js check if string in array
  13. jquery json to string
  14. javascript string to char array
  15. javascript array to string with spaces
  16. iso string to date
  17. parsestring
  18. javascript insert character into string
  19. javascript insert into string
  20. json.stringify array example
  21. storing array in localstorage

© 2023 Snyk Limited
Registered in England and Wales
Company number: 09677925
Registered address: Highlands House, Basingstoke Road, Spencers Wood, Reading, Berkshire, RG7 1NT.

Источник

Javascript array buffer to string

How to convert ArrayBuffer to and from String

Published on Thursday, June 14, 2012 • Updated on Saturday, February 9, 2019

Renato is a contributor to Chrome Developers

Update, August 2014: The Encoding API specification has matured, and a number of browsers now support it natively. The information in this article still applies for browsers that don’t yet support the Encoding API, but the recommended approach is to use the official API wherever possible. See Easier ArrayBuffer String conversion with the Encoding API for more details.

ArrayBuffers are used to transport raw data and several new APIs rely on them, including WebSockets, Web Intents 2](https://www.html5rocks.com/en/tutorials/file/xhr2/) and WebWorkers. However, because they recently landed in the JavaScript world, sometimes they are misinterpreted or misused.

Semantically, an ArrayBuffer is simply an array of bytes viewed through a specific mask. This mask, an instance of ArrayBufferView, defines how bytes are aligned to match the expected structure of the content. For example, if you know that the bytes in an ArrayBuffer represent an array of 16-bit unsigned integers, you just wrap the ArrayBuffer in a Uint16Array view and you can manipulate its elements using the brackets syntax as if the Uint16Array was an integer array:

// suppose buf contains the bytes [0x02, 0x01, 0x03, 0x07]
// notice the multibyte values respect the hardware endianess, which is little-endian in x86
var bufView = new Uint16Array(buf);
if (bufView[0]===258) // 258 === 0x0102
console.log("ok");
>
bufView[0] = 255; // buf now contains the bytes [0xFF, 0x00, 0x03, 0x07]
bufView[0] = 0xff05; // buf now contains the bytes [0x05, 0xFF, 0x03, 0x07]
bufView[1] = 0x0210; // buf now contains the bytes [0x05, 0xFF, 0x10, 0x02]

One common practical question about ArrayBuffer is how to convert a String to an ArrayBuffer and vice-versa. Since an ArrayBuffer is, in fact, a byte array, this conversion requires that both ends agree on how to represent the characters in the String as bytes. You probably have seen this «agreement» before: it is the String’s character encoding (and the usual «agreement terms» are, for example, Unicode UTF-16 and iso8859-1). Thus, supposing you and the other party have agreed on the UTF-16 encoding, the conversion code could be something like:

function ab2str(buf)  
return String.fromCharCode.apply(null, new Uint16Array(buf));
>
function str2ab(str)
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i strLen; i++)
bufView[i] = str.charCodeAt(i);
>
return buf;
>

Note the use of Uint16Array . This is an ArrayBuffer view that aligns bytes of the ArrayBuffers as 16-bit elements. It doesn’t handle the character encoding itself, which is handled as Unicode by String.fromCharCode and str.charCodeAt .

Note: A robust implementation of the String to ArrayBuffer conversion capable of handling more encodings is provided by the stringencoding library. But, for simple usage where you control both sides of the communication pipe, the code above is probably enough. A standardized API specification for String encoding is being drafted by the WHATWG working group.

A popular StackOverflow question about this has a highly voted answer with a somewhat convoluted solution to the conversion: create a FileReader to act as a converter and feed a Blob containing the String into it. Although this method works, it has poor readability and I suspect it is slow. Since unfounded suspicions have driven many mistakes in the history of humanity, let’s take a more scientific approach here. I have jsperf’ed the two methods and the result confirms my suspicion and you check out the demo here.

In Chrome 20, it is almost 27 times faster to use the direct ArrayBuffer manipulation code on this article than it is to use the FileReader / Blob method.

Updated on Saturday, February 9, 2019 • Improve article

Источник

skratchdot / arrayBufferToString.js

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

// source: http://stackoverflow.com/a/11058858
function ab2str ( buf )
return String . fromCharCode . apply ( null , new Uint16Array ( buf ) ) ;
>

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

// source: http://stackoverflow.com/a/11058858
function str2ab ( str )
var buf = new ArrayBuffer ( str . length * 2 ) ; // 2 bytes for each char
var bufView = new Uint16Array ( buf ) ;
for ( var i = 0 , strLen = str . length ; i < strLen ; i ++ )
bufView [ i ] = str . charCodeAt ( i ) ;
>
return buf ;
>

Good, but typescript complains that new Uint16Array(buf) cannot be converted to number[] .

Good, but typescript complains that new Uint16Array(buf) cannot be converted to number[] .

Use this code to convert an array buffer to a number

convertArrayBufferToNumber(buffer: ArrayBuffer)

Very good! Had to change the Uint16Array to Uint8Array and worked like a charm!

Use this code to convert an array buffer to a number

You can cast the Uint8Array (or any other ArrayBufferView) to number[] — it’s working fine in my case —

Why does it need to be Uint16Array ? What ‘s the cost of instantiating another ArrayBufferView ? is it minimal right ? I my case I work both with binary and text files and I read both using Uint8Array and this method works fine just passing it directly and in TypeScript I must cast to any:

const s = String.fromCharCode.apply(null, anArrayBufferView as any) 

I just posted a TS conversion of this: https://gist.github.com/AndrewLeedham/a7f41ac6bb678f1eb21baf523aa71fd5 feel free to use it. I used Array.from to convert the Uint16Array to a number[] . Casting will also work if you don’t want the extra operation.

 const byteArrayStringA = String.fromCharCode.apply(null, Array.from(new Uint8Array(anArrayBufferA))); 

const byteArrayString = String.fromCharCode.apply(null, Array.from(new Uint8Array(anArrayBufferB)));

 const byteArrayString = String.fromCharCode.apply(null, Array.from(new Uint8Array(anArrayBufferC))); 

The above code giving me «Maximum call stack size exceeded» error.
Please help

I am getting this error when i execute above code:

multipart.ts:33:30 — error TS2339: Property ‘charCodeAt’ does not exist on type ‘any[]’.

33 bufView[i] = post_data.charCodeAt(i);
~~~~~~~~~~

function str2ab(text)  return new TextEncoder().encode(text); >

@erycson — nice! It looks like TextEncoder/TextDecoder is now a global in node (as of v11.0.0). It was added in the util lib in v8.3.0.

Following your example. the ab2str function can be rewritten:

function ab2str(buf)  return new TextDecoder().decode(buf); >

Very good! Had to change the Uint16Array to Uint8Array and worked like a charm!

You can’t perform that action at this time.

Источник

Javascript array buffer to string

Convert ArrayBuffer to string with optional encoding.

npm install arraybuffer-to-string

var ab2str = require('arraybuffer-to-string')
var uint8 = new Uint8Array([ 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 ])
ab2str(uint8) // 'Hello World!'
ab2str(uint8, 'base64') // 'SGVsbG8gV29ybGQh'
ab2str(uint8, 'hex') // '48656c6c6f20576f726c6421'
ab2str(uint8, 'iso-8859-2') // 'Hello World!'

var str = arrayBufferToString(buffer, encoding=’utf8′)

Convert ArrayBuffer/ArrayBufferView/Array buffer to string with defined encoding. Available encoding: utf8 , binary , base64 , hex , ascii , latin1 , ucs2 , utf16 and many others.

Note: in browser it relies on TextDecoder API, so if you are dealing with charsets other than utf8 , ascii , binary or base64 in old browsers, please include encoding polyfill.

Источник

Читайте также:  Document
Оцените статью