ascii utf-8混合编码方式
设计一个ascii和utf-8 hybrid 的编码方式。
ascii
ASCII码一共规定了128个字符的编码。还有扩展的定义了128-255.
utf-8
unicode不定义存储格式。
UTF-8的编码规则很简单,只有二条:
- 对于单字节的符号,字节的第一位设为0,后面7位为这个符号的unicode码。因此对于英语字母,UTF-8编码和ASCII码是相同的。
- 对于n字节的符号(n>1),第一个字节的前n位都设为1,第n+1位设为0,后面字节的前两位一律设为10。剩下的没有提及的二进制位,全部为这个符号的unicode码。 下表总结了编码规则,字母x表示可用编码的位。
Char. number range | UTF-8 octet sequence
(hexadecimal) | (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
the advantage of choosing ASCII encoding over UTF-8
- string[] str 获取第i个char时不用判断前面字符是可变长
- 时间复杂度变大,程序更复杂
延生阅读:
- The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets(关于字符集的最基本知识)
- http://programmers.stackexchange.com/questions/97247/what-is-the-advantage-of-choosing-ascii-encoding-over-utf-8
- http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf-8.html