You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unreal Engine 5中如何将Shift-JIS编码字节数组转为FString?

在Unreal Engine 5中实现Shift-JIS字节数组转FString

一、使用平台API结合UE类型(推荐,无需额外依赖)

Shift-JIS是Windows平台常用编码,直接调用Windows API完成转码后,再转换为FString即可:

#include "Windows/WindowsPlatformMisc.h"
#include "Misc/Unicode.h"

FString ShiftJISBytesToFString(const TArray<uint8>& ShiftJISBytes)
{
    if (ShiftJISBytes.Num() == 0)
    {
        return FString();
    }

    // Shift-JIS对应的Windows代码页是932
    const UINT CodePage = 932;
    // 先获取所需宽字符数量
    int32 WideCharCount = MultiByteToWideChar(CodePage, 0, reinterpret_cast<const char*>(ShiftJISBytes.GetData()), ShiftJISBytes.Num(), nullptr, 0);
    if (WideCharCount == 0)
    {
        return FString();
    }

    TArray<wchar_t> WideChars;
    WideChars.SetNum(WideCharCount);
    // 执行转码
    MultiByteToWideChar(CodePage, 0, reinterpret_cast<const char*>(ShiftJISBytes.GetData()), ShiftJISBytes.Num(), WideChars.GetData(), WideCharCount);

    // FString内部基于UTF-16存储,可直接从wchar_t数组构造
    return FString(WideChars.GetData());
}

注意:该方法仅在Windows平台生效,若项目需跨平台,Linux等系统可替换为iconv API实现类似逻辑。

二、跨平台自定义转码实现

如果需要跨平台且不想依赖系统API,可自行实现Shift-JIS到Unicode的映射逻辑:

FString CustomShiftJISToFString(const TArray<uint8>& ShiftJISBytes)
{
    FString Result;
    int32 Index = 0;
    const int32 Length = ShiftJISBytes.Num();

    while (Index < Length)
    {
        uint8 Byte = ShiftJISBytes[Index];
        wchar_t UnicodeChar = 0;

        // 单字节ASCII范围(0x00-0x7F)
        if (Byte <= 0x7F)
        {
            UnicodeChar = Byte;
            Index++;
        }
        // 双字节字符的首字节范围:0x81-0x9F、0xE0-0xEF
        else if ((Byte >= 0x81 && Byte <= 0x9F) || (Byte >= 0xE0 && Byte <= 0xEF))
        {
            if (Index + 1 >= Length)
            {
                break; // 跳过不完整的双字节序列
            }
            uint8 SecondByte = ShiftJISBytes[Index + 1];
            // 此处需根据公开的Shift-JIS<->Unicode映射表完成码点转换
            // 示例仅占位,实际需替换为真实映射逻辑
            UnicodeChar = /* 计算得到的Unicode码点 */ 0x3042; // 对应日文"あ"
            Index += 2;
        }
        else
        {
            // 无效字节,直接跳过
            Index++;
            continue;
        }

        Result += UnicodeChar;
    }

    return Result;
}

提示:完整的Shift-JIS映射表可从官方编码标准文档获取,存入哈希表或数组可提升查询效率。

三、集成第三方编码库

若不想手动实现转码,可集成ICU(International Components for Unicode)这类成熟编码库。将库文件添加到UE项目后,使用其编码转换接口将Shift-JIS转为UTF-16,再直接构造FString即可(FString内部存储为UTF-16编码)。

内容的提问来源于stack exchange,提问作者Kane Mattsuki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 16:10:07