文章用JS简单的实现UTF-8编码和Base64编码,阅读本文可以了解Unicode 与 UTF-8 之间的转换,了解Base64编码为什么会使数据量变长。
概要:
- Unicode简单了解
- UTF-8编码
- Base64编码
- 总结
Unicode,ASCII,GB2312编码集合等,类似于字典。字符的编码,类似于字典中的字在哪一页哪一行。当不同系统用同一本字典查同一个编码得到的字符会一致。
如下图:
1. Unicode简单了解
Unicode is a computing industry standard for the consistent encoding, representation, and handling of text expressed in most of the world's writing systems.
在创造Unicode之前各种语言有不同的编码集合,ASCII,GB2312等也是发展过程中编码集合,而且这些编码集合相互冲突,给不同语言系统进行交流带来了麻烦。因为两种相同的字符在不同的编码系统中可能有完全不同的意思。于是Unicode出现了,Unicode编码集合给每个字符提供了一个唯一的数字,不论平台,程序,语言,Unicode 字符集因此被广泛应用。
Javascript程序是用Unicode字符集编写的, 字符串(string)中每个字符通常来自于Unicode 字符集。
Unicode 字符集类似于字典,字符就类似于字。字符的Unicode码值,就类似于字在字典的第页第几行。
2. utf8编码
2.1为何有了Unicode字符集还需要 一个编码来传输了?
因为Unicode 编码转换成二进制,是一串0,和1,传输个另一方的时候,需要一个规则来分割这一串0、1。
于是就出现了UTF-n 编码们。
8bit = 1byte
UTF(Universal Transformation Format,通用传输格式),其实就是不改变字符集中各个字符的代码,建立一套新的编码方式,把字符的代码通过这个编码方式映射成传输时的编码,最主要的任务就是在使用Unicode字符集保持通用性的同时节约流量和硬盘空间。
Unicode是一个符号集,规定了符号的二进制代码,没有规定这个二进制代码应该如何存储(即占用多少个字节)所以出现了不同的存储实现方式。
UTF-32
字符用四个字节表示
UTF-16字符用两个字节或四个字节表示
UTF-8
一种变长的编码方式,根据需要用1~4个字节来表示字符,(按需传递节约流量和硬盘空间,因此UTF-8用的比较广)
2.2UTF-8编码规则
- 对于单字节的符号,字节的第一位设为0,后面7位为这个符号的 Unicode 码。
- 对于n字节的符号(n > 1),第一个字节的前n位都设为1,第n+ 1位设为0,后面字节的前两位设为10。剩下,全部为这个符号的 Unicode 编码。
Unicode符号范围 | Unicode符号范围 | UTF-8编码方式 (十进制) | (十六进制) | (二进制) ---------------+----------------------+--------------------------------------------- 0 ~ 127 | 0000 0000-0000 007F | 0xxxxxxx 128 ~ 2047 | 0000 0080-0000 07FF | 110xxxxx 10xxxxxx 2048 ~ 65535 | 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx 65536 ~1114111 | 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
eg: 字符罗的UTF-8编码
用codePointAt得到了字符的Unicode 编码,确认用几个字节表示,然后按照规则填充。
编码流程:
资料补充:
ES6 提供了codePointAt()方法,能够正确处理字节储存的字符,返回一个字符的码点(Unicode 编码)。
ES6 提供了String.fromCodePoint()方法能正确处理一个码点(Unicode 编码),返回码点(Unicode 编码)对应的字符
2.3UTF-8编码解码简单实现
1 function encodeUtf8(str) { 2 var bytes = [] 3 for (ch of str) { 4 // for...of循环,能正确识别 32 位的 UTF-16 字符, 可以查阅资料了解。 5 let code = ch.codePointAt(0) 6 if (code >= 65536 && code <= 1114111) {// 位运算, 补齐8位 7 bytes.push((code >> 18) | 0xf0) 8 bytes.push(((code >> 12) & 0x3f) | 0x80) 9 bytes.push(((code >> 6) & 0x3f) | 0x80) 10 bytes.push((code & 0x3f) | 0x80) 11 } else if (code >= 2048 && code <= 65535) { 12 bytes.push((code >> 12) | 0xe0) 13 bytes.push(((code >> 6) & 0x3f) | 0x80) 14 bytes.push((code & 0x3f) | 0x80) 15 } else if (code >= 128 && code <= 2047) { 16 bytes.push((code >> 6) | 0xc0) 17 bytes.push((code & 0x3f) | 0x80) 18 } else { 19 bytes.push(code) 20 } 21 } 22 return bytes 23 } 24 function padStart(str, len, prefix) { 25 return ((new Array(len + 1).join(prefix)) + str).slice(-len) // 也可用 new Array(len+1).fill(0) 26 } 27 function decodeUtf8(str) { 28 let strValue = '' 29 let obStr = [...str].map((ch)=> { 30 return padStart(parseInt(ch,16).toString(2), 4, 0) 31 }).join('').match(/\d{8}/g).map((item)=> parseInt(item,2)) 32 for (var i = 0; i < obStr.length; ) { 33 34 let code = obStr[i] 35 let code1, code2, code3, code4, hex 36 if ((code & 240) == 240) { 37 code1 = (code & 0x03).toString(2) 38 code2 = padStart((obStr[i + 1] & 0x3f).toString(2),6, '0') 39 code3 = padStart((obStr[i + 2] & 0x3f).toString(2),6, '0') 40 code4 = padStart((obStr[i + 3] & 0x3f).toString(2),6, '0') 41 hex = parseInt((code1 + code2 + code3 + code4),2) 42 strValue = strValue + String.fromCodePoint(hex) 43 i = i + 4 44 } else if ((code & 224) == 224) { 45 code1 = (code & 0x07).toString(2) 46 code2 = padStart((obStr[i + 1] & 0x3f).toString(2),6, '0') 47 code3 = padStart((obStr[i + 2]& 0x3f).toString(2),6, '0') 48 hex = parseInt((code1 + code2 + code3),2) 49 strValue = strValue + String.fromCodePoint(hex) 50 i = i + 3 51 } else if ((code & 192) == 192) { 52 code1 = (code & 0x0f).toString(2) 53 code2 = padStart((obStr[i + 1] & 0x3f).toString(2),6, '0') 54 hex = parseInt((obStr + code2),2) 55 strValue = strValue + String.fromCodePoint(hex) 56 i = i + 2 57 } else { 58 hex = code 59 strValue = strValue + String.fromCodePoint(code) 60 i = i + 1 61 } 62 } 63 return strValue 64 } 65 function transferHex(bytes) { 66 let s = '' 67 bytes && 68 bytes.forEach(ch => { 69 s = s + ch.toString(16) 70 }) 71 return s 72 } 73 let text = "罗小步 啊哈哈 𠮷 ssdf 34534 ASD" 74 let strHax = transferHex(encodeUtf8(text)) 75 console.log(strHax) 76 let str = decodeUtf8(strHax) 77 console.log(str) 78 79 console.log("test ok?", text === str)
3. Base64 编码
3.1Base64编码规则
规则:Base64的编码方法要求把每三个8bit的字节转换成四个6bit的字节,然后把6Bit再添两位高位0,组成四个8Bit的字节。
如果要编码的二进制数据不是3的倍数,最后剩下一个或者两个字节base64会在末尾补零,再在编码的末尾加上一个或者两个‘=’。
每个8bit 编码成:CHARST[paresInt(8bit ,2)]
CHARTS = ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
简单流程的:
3.2 Base64编码简单实现
1 const CHARTS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; 2 const prefix = '=' 3 const prefixTwo = 2 4 const prefixfour = 4 5 function padEnd(str, len, prefix) { 6 return (str + (new Array(len + 1)).join(prefix)).slice(0, len) 7 } 8 function padStart(str, len, prefix) { 9 return ((new Array(len + 1).join(prefix)) + str).slice(-len) 10 } 11 function encodeBase64(str){ 12 let byteStr = '' 13 for(let ch of encodeUtf8(str)){ 14 byteStr = byteStr + padStart(ch.toString(2),8,0) 15 } 16 let rest = byteStr.length % 6 // 余2 就是剩下了一个字节,余 4 就是剩下两个字节 17 let restStr = rest === prefixTwo ? '==' :'=' 18 let prefixzero = rest === prefixTwo ? prefixfour: prefixTwo 19 byteStr = padEnd(byteStr , byteStr.length + prefixzero,'0') 20 return byteStr.match(/(\d{6})/g).map(val=>parseInt(val,2)).map(val=>CHARTS[val]).join('') + restStr; 21 } 22 23 function decodeBase64(str) { 24 let matchTime = str.match(/(ha)/g) 25 26 let [...restStr] = str.replace(/=/g,'') 27 restStr = restStr.map((item)=> { 28 let value = CHARTS.indexOf(item) 29 return padStart(value.toString(2),6,0) 30 }).join('').match(/(\d{8})/g).map((item)=>parseInt(item,2).toString(16)).join() 31 console.log(restStr) 32 return decodeUtf8(restStr) 33 } 34 35 let text = "罗小步 啊哈哈 𠮷 ssdf 34534 ASD" 36 let strHax = encodeBase64(text) 37 console.log(strHax) 38 let str = decodeBase64(strHax) 39 console.log(str) 40 41 console.log("test ok?", text === str)
Base64的编码方法要求把每三个8bit的字节转换成四个6bit的字节,编码会使数据量变长原来的1/3.
4. 总结
编码方式只是一种对字符集表现的形式。文章用js 简单的实现utf8编码和base64编码。代码实现比较粗糙,理解不准确之处,还请教正。欢迎一起讨论学习。