Skip to content
Go back

codec in js

Published:  at  17:00

On this page

编码

ASCII

GB2312

2个字节表示一个字符(256 x 256 = 65536) 收录了六千多个常用的简体汉字及一些符号,数字,拼音等字符

Unicode

字符集标准,将世界上所有的符号都纳入其中。每一个符号都给予一个独一无二的编码

范围是 0x0000 - 0x10FFFF , 可以容纳一百多万个字符

utf-8

https://asecuritysite.com/coding/asc2

规则

Unicode符号范围 (十六进制)UTF-8编码方式(二进制)
0000 0000-0000 007F0xxxxxxx
0000 0080-0000 07FF110xxxxx 10xxxxxx
0000 0800-0000 FFFF1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

method

btoa & atob

String.prototype.charCodeAt

返回 0 到 65535 之间的整数,表示给定索引处的 UTF-16 代码单元

String.prototype.codePointAt

返回 一个 Unicode 编码点值的非负整数

''.codePointAt(0)  // 20005
// 严的 Unicode 是4E25 4E25 转十进制就是20005

String.fromCharCode

返回由指定的 UTF-16 代码单元序列创建的字符串,范围介于 0655350xFFFF)之间

String.fromCharCode(65, 66, 67);   // 返回 "ABC"
String.fromCharCode(0x2014);       // 返回 "—"
String.fromCharCode(0x12014);      // 也是返回 "—"; 数字 1 被剔除并忽略
String.fromCharCode(8212);         // 也是返回 "—"; 8212 是 0x2014 的十进制表示

String.fromCodePoint

返回使用指定的代码点序列创建的字符串

String.fromCodePoint(42);       // "*"
String.fromCodePoint(65, 90);   // "AZ"

escape & unescape

生成新的由十六进制转义序列替换的字符串

排除:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./

当该值小于等于 0xFF 时,用一个 2 位转义序列: %xx 表示。大于的话则使用 4 位序列:%uxxxx 表示

escape("abc123");     // "abc123"
escape('') // '%u4E25'

encodeURI & decodeURI

对应的 Unicode 的 UTF-8 编码的十六进制格式

排除:

// 严 > 4E25 > E4B8A5 > %E4%B8%A5
encodeURI('') //'%E4%B8%A5'

因为 ”&”, ”+”, 和 ”=” 不会被编码,然而在 GET 和 POST 请求中它们是特殊字符

encodeURIComponent & decodeURIComponent

排除:

实践


原因是window.atob()不支持unicode字符  
所以需要修改为  
rawdata = decodeURIComponent(escape(window.atob(str)))  
  
  反之亦然  
  data = window.btoa(unescape(encodeURIComponent(str)))  


  // 编码中文 → Base64
function encodeChinese(str) {
  const encoder = new TextEncoder();
  const bytes = encoder.encode(str);
  return btoa(String.fromCharCode(...bytes));
}


function decodeChinese(base64) {
  const binaryStr = atob(base64);
  const bytes = new Uint8Array([...binaryStr].map(c => c.charCodeAt(0)));
  const decoder = new TextDecoder('utf-8');
  return decoder.decode(bytes);
}

Suggest Changes

Previous Post
access b2 through cloudflare

Most Related Posts

  • low code

    Published:  at  20:30

    low code

  • javascript scope

    Published:  at  13:14

    javascript scope

  • highlighter maker

    Published:  at  23:29

    highlighter maker

  • WSL 基本使用

    Published:  at  12:40

    WSL (Windows Subsystem for Linux) 的基本安装、配置、使用方法以及常见问题的解决方案。

  • css

    Published:  at  20:39

    css