We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
在浏览器端,我们可以利用btoa来转换,其定义如下:
let encodedData = window.btoa(stringToEncode);
btoa会自动将stringToEncode转换为base64编码的ASCII字符串:
btoa
stringToEncode
window.btoa('Hello, World') // SGVsbG8sIFdvcmxk
虽然字面上是文本,但其实也是“二进制”转base64。
如果输入内容是一串8位比特字符串:
"1001000,1100101,1101100,1101100,1101111,101100,100000,1010111,1101111,1110010,1101100,1100100"
为了方便处理,这里用逗号分隔。
// 比特串转为文本 const binaryStringToText = binaryString => { return binaryString.split(',').map(b => { return String.fromCharCode(parseInt(b, 2)); }).join(''); }; const binaryStringToBase64 = binaryString => { let text = binaryStringToText(binaryString); return window.btoa(text); }; binaryStringToBase64("1001000,1100101,1101100,1101100,1101111,101100,100000,1010111,1101111,1110010,1101100,1100100"); // SGVsbG8sIFdvcmxk
如果输入内容是一串ASCII码值:
72,101,108,108,111,44,32,87,111,114,108,100
我们换一种方式来处理,使用Uint8Array:
const binaryStringToText = binaryString => { let data = binaryString.split(',').map(v => +v); return String.fromCharCode(...new Uint8Array(data)); }; const binaryStringToBase64 = binaryString => { let text = binaryStringToText(binaryString); return window.btoa(text); }; binaryStringToBase64("72,101,108,108,111,44,32,87,111,114,108,100"); // SGVsbG8sIFdvcmxk
base64转为字符串,首先需要通过atob来解码,其定义如下:
var decodedData = window.atob(encodedData);
如果传入字符串不是有效的 base64 字符串,比如其长度不是 4 的倍数,则抛出DOMException。
DOMException
const base64ToBinary = base64 => { let text = window.atob(base64); let textLength = text.length; let array = new Uint8Array(new ArrayBuffer(textLength)); for(i = 0; i < textLength; i++) { array[i] = text.charCodeAt(i); } return array; } let uInt8Array = base64ToBinary('SGVsbG8sIFdvcmxk'); // Uint8Array(12) [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100] binaryStringToText(uInt8Array.toString()); // Hello, World
The text was updated successfully, but these errors were encountered:
如果是纯JS实现,请参考js-base64。
Sorry, something went wrong.
base64编码算法,请参考Base64。
No branches or pull requests
base64编码
在浏览器端,我们可以利用btoa来转换,其定义如下:
btoa
会自动将stringToEncode
转换为base64编码的ASCII字符串:虽然字面上是文本,但其实也是“二进制”转base64。
如果输入内容是一串8位比特字符串:
为了方便处理,这里用逗号分隔。
如果输入内容是一串ASCII码值:
我们换一种方式来处理,使用Uint8Array:
base64解码
base64转为字符串,首先需要通过atob来解码,其定义如下:
如果传入字符串不是有效的 base64 字符串,比如其长度不是 4 的倍数,则抛出
DOMException
。The text was updated successfully, but these errors were encountered: