Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of base64 conversion examples in JavaScript

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of base64 conversion case analysis in JavaScript, the content is detailed and easy to understand, the operation is simple and fast, and it has a certain reference value. I believe you will gain something after reading this JavaScript conversion case analysis article. Let's take a look at it.

Base64 is actually a kind of transcoding method, which converts ASCII characters into plain text. It is one of the most common encodings used to transmit 8Bit bytecodes on the network.

Base64 consists of the letters Amurz, Amurz, 0-9 and + and /, plus = as a cushion, a total of 65 characters form a basic character set, and all other characters can be converted into characters in that character set according to certain rules.

Abcde = > YWJjZGU= ABCDE = > QUJDREU=

In daily development, the most common thing is to convert blob and base64 to each other.

/ / blob to base64function blobTobase64 (blob) {const fileReader = new FileReader () let base64 =''fileReader.onload = () = > {base64 = fileReader.result / / read base64} fileReader.readAsDataURL (blob) / / read blob} / / base64 to blobfunction dataURItoBlob (dataURI) {var mimeString = dataURI .split (',') [0] .split (':') [1] .split (' ') [0] / / mime type var byteString = atob (dataURI.split (',') [1]) / / base64 decoding var arrayBuffer = new ArrayBuffer (byteString.length) / / create ArrayBuffer var intArray = new Uint8Array (arrayBuffer) / / create view for (var I = 0; I

< byteString.length; i++) { intArray[i] = byteString.charCodeAt(i) } return new Blob([intArray], { type: mimeString }) // 转成 blob} 编码和解码 浏览器 最新的浏览器自带了两个方法用于 base64 的编码和解码 分别是 at ob 和 btoa atob:将 base64 转成 8bit 字节码 btoa:将 8bit 字节码转成 base64 对于旧版浏览器, 可以使用 js-base64 Node 目前 node 中还不支持使用 atob 和 btoa ,但是可以通过 Buffer 来实现,参考文档 if (typeof btoa === 'undefined') { global.btoa = function (str) { return Buffer.from(str).toString('base64'); };}if (typeof atob === 'undefined') { global.atob = function (b64Encoded) { return Buffer.frome(b64Encoded, 'base64').toString(); };} 转换方式 base64编码方式对于中文是不适用的, 因为中文对应多个字节, 因此可以先使用 encodeURIComponent 编码后再进行 base64 编码. 源码 编码 每三个字节作为一组,每个字节8bit, 一共是24个二进制位。 'ABCD'["ABC", "D"] // 每三字节做一组['01000001010000100100001', '01000100'] // 转成8bit 将每组的24个二进制位再细分为四组,每组有6个二进制位, 此时为二维数组。 [['010000', '010100', '001001', '000011'], ['010001', '00']] 二个字节的情况:将这二个字节的一共16个二进制位, 按照上面的规则, 转成三组, 那么最后一项只有4位,则在后面加两个0, 补够6位, 并在第三步对应位置加上垫字符 = 。 一个字节的情况:将这一个字节的8个二进制位,按照上面的规则转成二组, 那么最后一项只有2位, 则在后面加上四个0, 并在第三步对应位置加上两个垫字符 = 。 简单说就是, 缺多少位就在后面补多少个0, 直到满6位。 [['010000', '010100', '001001', '000011'], ['010001', '000000']] 在每组前面加两个00,扩展成32个二进制位,即四个字节。 规则是这么说, 但这一步我觉得可以忽略, 因为 00101010 和 101010 是一样的 将每组对应的二进制转成十进制, 在 base64char 字符集中找到对应的字符。 [["Q", "U", "J", "D"], ["R", "A"]] 每一组都最终都应该转成四个字符 如果不足四个字符, 说明明文中并不足3字节, 因此需要补上垫字符 = , 补够四个字符 [["Q", "U", "J", "D"], ["R", "A", "=", "="]] 将最后的结果连接成字符串, 则为最终编码结果。 'ABCD' >

'QUJDRA=='

According to the encoding method, every 3 bytes will be encoded into four characters. If it is less than 3 bytes, the cushion character = will be added, and if there are a few missing, a few will be added.

Btoa ('A') / / "QQ==" btoa ('AB') / / "QUI=" btoa (' ABC') / / "QUJD" btoa ('ABCD') / / "QUJDRA=="

Decode

The decoding step is the opposite of the coding step.

Every four bytes is divided into a group.

Find the subscript in each set of characters except the pad character = in the base64char character set.

Convert the decimal subscript to binary, and if it is less than 6 bits (definitely not more than 6 bits), add 0 in front.

If the pad character = is encountered, which means that the plaintext is less than 3 bytes, 0 of the corresponding number is removed from the last item of the group according to the number of pad characters =.

If one pad character is used, two zeros are removed

If there are two pad characters, four zeros will be removed.

Concatenate the binary strings in each group, where the string length must be a multiple of 8, and then split every 8 bits into one byte.

Convert binaries to characters through String.fromCharCode and then splice them together

Connect each character for the final decoding result.

Off-topic-to-binary conversion

ParseInt (str, radix): string can be converted to decimal according to radix

InitValue.toString (radix): convert initValue to other binary

/ / n-to-decimal parseInt ('1000, 2) / / 8parseInt (' 1000, 16) / / 4096 bound / inter-binary conversion (10) .toString (2) / "1010", 10-to-2 (0xff) .toString (2) / / "11111111", hexadecimal to binary on the analysis of base64 conversion examples in JavaScript, this is the end of the article. Thank you for reading! I believe you all have a certain understanding of the knowledge of "case Analysis of base64 conversion in JavaScript". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report