我有一个C++/UnrealEngine客户端,可以与现有的C#服务器和现有的JavaScript服务器(全部在Windows上)进行对话.
我的问题是当我用C++对Guid进行Base 64编码时,我从C#和JS得到不同的结果.据我所知,这与this SO answer中提到的Guid字符串的编码方式直接相关.
我无法真正更改C#和JS服务器,因为它们有其他依赖系统,那么我需要在C++(或Unreal)中做什么才能确保得到相同的输出?
//The Guid as a literal string
"3F73B3E6-7351-416F-ACA3-AE639A3F587F"
//C# & JSEncoded
"5rNzP1Fzb0Gso65jmj9Yfw"
//C++ Encoded
"P3Oz5nNRQW+sowAArmOaPw"
此外,使用在线转换器(判断自己的健康状况)我会得到相同的两个不同的结果,所以似乎没有真正标准化的方式.
//https://rcfed.com/Utilities/Base64GUID
//https://toolslick.com/conversion/data/guid
"5rNzP1Fzb0Gso65jmj9Yfw"
//https://www.fileformat.info/tool/guid-base64.htm
"P3Oz5nNRQW+sowAArmOaPw"
用于转换的代码如下:
//In C#
Guid myGuid = new Guid("3F73B3E6-7351-416F-ACA3-AE639A3F587F");
//Encodes / & + for URL & truncates the trailing "==" padding
string strBase64Guid = Convert.ToBase64String(myGuid.ToByteArray()).Substring(0, 22).Replace("/", "_").Replace("+", "-");
//In JavaScript
//https://stackoverflow.com/questions/55356285/how-to-convert-a-string-to-base64-encoding-using-byte-array-in-javascript
var strGuid = GuidToBase64("3F73B3E6-7351-416F-ACA3-AE639A3F587F");
function GuidToBase64(guid){
//Guid to ByteArray
var buffer = [];
guid.split('-').map((number, index) => {
var bytesInChar = index < 3 ? number.match(/.{1,2}/g).reverse() : number.match(/.{1,2}/g);
bytesInChar.map((byte) => { buffer.push(parseInt(byte, 16)); })
});
var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)));
//Encodes / & + for URL & truncates the trailing "==" padding
return base64String.slice(0, 22).replace("/", "_").replace("+", "-");
}
//In C++ (Unreal Engine)
FGuid& myGuid = FGuid("3F73B3E6-7351-416F-ACA3-AE639A3F587F");
FString& strGuid = myGuid.ToString(EGuidFormats::Short);
//Copyright Epic Games, Inc. (AFAIK I'm allowed to paste snippets from the sources, just not the whole thing. UE's source it's all on GitHub anyway.)
//Truncated [Function overloads, & Guid format handling]
uint32 Bytes[4] = { NETWORK_ORDER32(A), NETWORK_ORDER32(B), NETWORK_ORDER32(C), NETWORK_ORDER32(D) };
TCHAR Buffer[25];
int32 Len = FBase64::Encode(reinterpret_cast<const uint8*>(Bytes), sizeof(Bytes), Buffer);
TArrayView<TCHAR> Result(Buffer, Len);
//Truncated [Sanitizes '+' & '/' and cuts the '==' padding]
}