js base64的转码与解码

2021-04-10 06:27

阅读:813

标签:first   tin   ror   info   window   nts   error:   超过   org   

使用方法window.btoa 将字符串转为base64编码

使用方法window.atob 将base64编码转为js字符串

 

 

var string = “Hello World”

let base64 = window.btoa(string)

let str = window.atob(base64)

 

注意:

javascript中的字符实现一般是16位无符号整数

 

使用方法window.btoa 将字符串转为base64编码

使用方法window.atob 将base64编码转为js字符串

 

 

var string = “Hello World”

let base64 = window.btoa(string)

let str = window.atob(base64)

 

注意:

javascript中的字符实现一般是16位无符号整数

 

 

使用方法window.btoa 将字符串转为base64编码

使用方法window.atob 将base64编码转为js字符串

 

 

var string = “Hello World”

let base64 = window.btoa(string)

let str = window.atob(base64)

 

注意:

javascript中的字符的实现一般是16位无符号整数

技术图片

 

 

 

(http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.1)

 

 

ascii编码是8位的,所以,如果是超过8位的,比如unicode中的中文就会报错

 

(

  • btoa() accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probablybreak. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.
  • atob() returns a “string” where each character represents an 8-bit byte – that is, its value will be between 0 and 0xff. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.

)

 

let str = ‘我叫

window.btoa(str) // InvalidCharacterError: String contains an invalid character

 

可以先将unicode text转换为utf-8编码(encodeURIComponent),然后使用base64编码,解码的时候再转换回来,就能得到原先的text

 

注意:

encodeURIComponent的转义范围比encodeURI更大

js base64的转码与解码

标签:first   tin   ror   info   window   nts   error:   超过   org   

原文地址:https://www.cnblogs.com/eret9616/p/12432047.html


评论


亲,登录后才可以留言!