是否可以仅使用 Windows API 将 UTF32 文本转换为 UTF16? [英] Is it possible to convert UTF32 text to UTF16 using only Windows API?

查看:32
本文介绍了是否可以仅使用 Windows API 将 UTF32 文本转换为 UTF16?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到可以单独使用 Windows API 将 UTF-32 文本转换为/从任何代码页.我无法使用 CLR 来执行此任务.

I'm trying to find converting UTF-32 text to/from any code page is possible using the Windows API alone. I cannot used CLR to do this task.

Microsoft 的代码页标识符页面 http://msdn.microsoft.com/en-us/library/dd317756(VS.85).aspx 将 UTF-32 列为仅可用于托管应用程序.

The Code page identifiers page at Microsoft at http://msdn.microsoft.com/en-us/library/dd317756(VS.85).aspx lists UTF-32 as being available to only managed applicatiosn.

ConvertStringTo/FromUnicode 在使用 UTF-32 时失败.

ConvertStringTo/FromUnicode fails when UTF-32 is used.

推荐答案

您可以使用此函数将 UTF-32 代码点转换为等效的 UTF-16 代码点(单个或代理,视情况而定)作为第一个参数和高和低代理作为第二和第三个参数.高低代理值通过引用返回.

You can use this function that takes the UTF-32 codepoint to be converted to it's equivalent UTF-16 codepoint (single or surrogate as the case may be) as the first argument and the high and low surrogates as second and third arguments. The high and low surrogate values are returned by reference.

如果代码点低于 0x10000,那么我们只需通过引用返回低代理中的代码点,而高代理是 0.

If the codepoint is below 0x10000, then we simply return that codepoint in the low surrogate by reference while the high surrogate is 0.

如果代码点大于 0x10000,则我们使用此维基百科页面上给出的规则计算高低代理对:

If the codepoint is greater than 0x10000, then, we calculate the high and low surrogate pairs using the rules given on this wikipedia page:

https://en.wikipedia.org/wiki/UTF-16#Example_UTF-16_encoding_procedure

代码如下:

unsigned int convertUTF32ToUTF16(unsigned int cUTF32, unsigned int &h, unsigned int &l)
{
    if (cUTF32 < 0x10000)
    {
        h = 0;
        l = cUTF32;
        return cUTF32;
    }
    unsigned int t = cUTF32 - 0x10000;
    h = (((t<<12)>>22) + 0xD800);
    l = (((t<<22)>>22) + 0xDC00);
    unsigned int ret = ((h<<16) | ( l & 0x0000FFFF));
    return ret;
}

这篇关于是否可以仅使用 Windows API 将 UTF32 文本转换为 UTF16?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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