Javascript编码打破&组合多字节字符? [英] Javascript encoding breaking & combining multibyte characters?

查看:191
本文介绍了Javascript编码打破&组合多字节字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算为我的网络应用程序使用客户端AES加密。



现在,我一直在寻找破解多字节字符的方法加密(以具有相同的加密文本长度),



将它们解密,将它们转换为一个字节的'非字符'



我已经看过维基的UTF-8(据称是默认编码的JS?)和UTF-16,但我可以



感谢:)

解决方案

JavaScript字符串是UTF -16存储在16位字符。对于需要超过16位(一些代码点在UTF-16中需要32位)的Unicode字符(代码点),每个JavaScript字符实际上只是代码点的一半。



因此,为了将JavaScript字符断开为字节,只需取出字符代码并拆分高字节和低字节:

  var code = str.charCodeAt(0); //第一个字符,显然你将有一个循环
var lowbyte = code& 0xFF;
var highbyte =(code& 0xFF00)> 8;

(即使JavaScript的数字是浮点数,位运算符以32位整数,当然在我们的例子中只有16位是相关的。)



你永远不会有奇数个字节,因为这是UTF-16。 / p>

I'm planning to use a client-side AES encryption for my web-app.

Right now, I've been looking for ways to break multibyte characters into one byte-'non-characters' ,encrypt (to have the same encrypted text length),

de-crypt them back, convert those one-byte 'non-characters' back to multibyte characters.

I've seen the wiki for UTF-8 (the supposedly-default encoding for JS?) and UTF-16, but I can't figure out how to detect "fragmented" multibyte characters and how I can combine them back.

Thanks : )

解决方案

JavaScript strings are UTF-16 stored in 16-bit "characters". For Unicode characters ("code points") that require more than 16 bits (some code points require 32 bits in UTF-16), each JavaScript "character" is actually only half of the code point.

So to "break" a JavaScript character into bytes, you just take the character code and split off the high byte and the low byte:

var code = str.charCodeAt(0); // The first character, obviously you'll have a loop
var lowbyte = code & 0xFF;
var highbyte = (code & 0xFF00) >> 8;

(Even though JavaScript's numbers are floating point, the bitwise operators work in terms of 32-bit integers, and of course in our case only 16 of those bits are relevant.)

You'll never have an odd number of bytes, because again this is UTF-16.

这篇关于Javascript编码打破&组合多字节字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆