forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBase64ToArrayBuffer.js
More file actions
Latest commit
48 lines (41 loc) · 1.89 KB
/
Copy pathBase64ToArrayBuffer.js
File metadata and controls
48 lines (41 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// About base64: https://en.wikipedia.org/wiki/Base64
/**
* Converts a base64 string to an array of bytes
* @param {string} b64 A base64 string
* @returns {ArrayBuffer} An ArrayBuffer representing the bytes encoded by the base64 string
*/
functionbase64ToBuffer(b64){
// The base64 encoding uses the following set of characters to encode any binary data as text
constbase64Table=
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
// Find the index of char '=' first occurrence
constpaddingIdx=b64.indexOf('=')
// Remove padding chars from base64 string, if there are any
constb64NoPadding=paddingIdx!==-1 ? b64.slice(0,paddingIdx) : b64
// Calculate the length of the result buffer
constbufferLength=Math.floor((b64NoPadding.length*6)/8)
// Create the result buffer
constresult=newArrayBuffer(bufferLength)
// Create an instance of Uint8Array, to write to the `result` buffer
constbyteView=newUint8Array(result)
// Loop through all chars in the base64 string, in increments of 4 chars, and in increments of 3 bytes
for(leti=0,j=0;i<b64NoPadding.length;i+=4,j+=3){
// Get the index of the next 4 base64 chars
constb64Char1=base64Table.indexOf(b64NoPadding[i])
constb64Char2=base64Table.indexOf(b64NoPadding[i+1])
letb64Char3=base64Table.indexOf(b64NoPadding[i+2])
letb64Char4=base64Table.indexOf(b64NoPadding[i+3])
// If base64 chars 3 and 4 don't exit, then set them to 0
if(b64Char3===-1)b64Char3=0
if(b64Char4===-1)b64Char4=0
// Calculate the next 3 bytes
constbyte1=(b64Char1<<2)+((b64Char2&48)>>4)
constbyte2=((b64Char2&15)<<4)+((b64Char3&60)>>2)
constbyte3=((b64Char3&3)<<6)+b64Char4
byteView[j]=byte1
byteView[j+1]=byte2
byteView[j+2]=byte3
}
returnresult
}
export{base64ToBuffer}