如何提高 UTF32 到 UTF16 代理对转换器的性能 [英] How can I improve performance of UTF32 to UTF16 surrogate pair converter

查看:43
本文介绍了如何提高 UTF32 到 UTF16 代理对转换器的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下转换器对不在正常"平面中的 Unicode 字符进行拆分.

I am using following converter to do the splits of Unicode chars not in 'normal' plane.

function toUTF16Pair(x) {
        var first = Math.floor((x - 0x10000) / 0x400) + 0xD800;
        var second = ((x - 0x10000) % 0x400) + 0xDC00;
        return '\\u'+first.toString(16) + '\\u'+second.toString(16);
}

我正在寻求性能改进(如果可能的话).

I am looking for performance improvement (if one is possible).

推荐答案

像往常一样,我自己使用了一些二进制魔法.请尝试击败它.

As usual did it myself with some binary magic. Please try to beat this.

function toUTF16Pair(x) {
    return '\\u' + ((((x - 0x10000) >> 0x0a) | 0x0) + 0xD800).toString(16) 
         + '\\u' + (((x - 0x10000) & 0x3FF) + 0xDC00).toString(16)
}

如果有人想知道它是如何工作的:
<代码>>>0x0a - 二进制右移 10 个位置,相当于除以 1024.
<代码>|0x0 - 相当于 Math.floor
<代码>&0x3FF - 因为 2 的模可以表示为 (x % n == x & (n - 1)),在我的例子中是 &1063 十进制.

In case anyone is wondering how it works:
>> 0x0a - is binary right shift 10 positions that is equivalent to division by 1024.
| 0x0 - is equivalent of Math.floor
& 0x3FF - because modulo of 2 can be expressed as (x % n == x & (n - 1)) which in my case is & 1063 in decimal.

希望这可以为您节省一些时间.

Hope this saves you some time.

这篇关于如何提高 UTF32 到 UTF16 代理对转换器的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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