MCPcopy Create free account
hub / github.com/cryptii/cryptii / base64StringFromBytes

Method base64StringFromBytes

src/ByteEncoder.js:109–165  ·  view source on GitHub ↗

* Returns base64 string representing given bytes. * @param {Uint8Array} bytes Bytes * @param {object} [options] Base64 options * @param {string} [options.alphabet] Base64 alphabet * @param {string} [options.padding='='] Padding character * @param {boolean} [options.paddingOptional=fal

(bytes, options = {})

Source from the content-addressed store, hash-verified

107 * @return {string} Base64 string
108 */
109 static base64StringFromBytes (bytes, options = {}) {
110 // Compose options
111 const {
112 alphabet,
113 padding,
114 paddingOptional,
115 maxLineLength,
116 lineSeparator
117 } = Object.assign({}, defaultBase64Options, options)
118
119 // Choose padding
120 const paddingCharacter = !paddingOptional && padding ? padding : ''
121
122 // Encode each 3-byte-pair
123 let string = ''
124 let byte1, byte2, byte3
125 let octet1, octet2, octet3, octet4
126
127 for (let i = 0; i < bytes.length; i += 3) {
128 // Collect pair bytes
129 byte1 = bytes[i]
130 byte2 = i + 1 < bytes.length ? bytes[i + 1] : NaN
131 byte3 = i + 2 < bytes.length ? bytes[i + 2] : NaN
132
133 // Bits 1-6 from byte 1
134 octet1 = byte1 >> 2
135
136 // Bits 7-8 from byte 1 joined by bits 1-4 from byte 2
137 octet2 = ((byte1 & 3) << 4) | (byte2 >> 4)
138
139 // Bits 4-8 from byte 2 joined by bits 1-2 from byte 3
140 octet3 = ((byte2 & 15) << 2) | (byte3 >> 6)
141
142 // Bits 3-8 from byte 3
143 octet4 = byte3 & 63
144
145 // Map octets to characters
146 string +=
147 alphabet[octet1] +
148 alphabet[octet2] +
149 (!isNaN(byte2) ? alphabet[octet3] : paddingCharacter) +
150 (!isNaN(byte3) ? alphabet[octet4] : paddingCharacter)
151 }
152
153 if (maxLineLength) {
154 // Limit text line length, insert line separators
155 let limitedString = ''
156 for (let i = 0; i < string.length; i += maxLineLength) {
157 limitedString +=
158 (limitedString !== '' ? lineSeparator : '') +
159 string.substr(i, maxLineLength)
160 }
161 string = limitedString
162 }
163
164 return string
165 }
166

Callers 4

ByteEncoder.jsFile · 0.80
serializeMethod · 0.80
performEncodeMethod · 0.80
serializeValueMethod · 0.80

Calls 1

substrMethod · 0.80

Tested by

no test coverage detected