UE4 C++ 10进制转16进制字符串
最近在处理 动感平台的输入值,需要16进制
现在就来记录下。
.h
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "BPF_16StringByte.generated.h"
UCLASS()
class THIRDPERSONTEST_API UBPF_16StringByte : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "DecimalConvert")
static void show16bit(int num,FString& ss);
UFUNCTION(BlueprintCallable, Category = "DecimalConvert")
static TArray<uint8> hexToBytes(FString hex);
};
.cpp
#include <string>
#include "BPF_16StringByte.h"
using namespace std;
const string HEX = "0123456789abcdef";
void UBPF_16StringByte::show16bit(int num, FString& ss) //10进制转换16进制
{
/*
十六进制数是在程序设计时经常要使用到的一种整数的表示方式。
它有0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F共16个符号
分别表示十进制数的0至15。十六进制的计数方法是满16进1
所以十进制数16在十六进制中是10,而十进制的17在十六进制中是11,以此类推,十进制的30在十六进制中是1E。
给出一个非负整数,将它表示成十六进制的形式。
输入包含一个非负整数a,表示要转换的数。0<=a<=2147483647
*/
// &0x0f 表示跟二进制的16相与 == %16;
// >>=4 表示右移4位(缩小2的4次方倍),因为二进制的每一位都表示2的1次方倍大。
string result;
int count = 0;
if (num == 0)
{
result = "0";
}
while (num&&count++<8)
{
result = HEX[(num & 0x0f)]+result;
num >>= 4;
}
ss = result.c_str();
}
16进制字符串再转Byte数组
TArray<uint8> UBPF_16StringByte::hexToBytes(FString hex)
{
TArray<uint8> tc;
std::string strByte = TCHAR_TO_UTF8(*hex);
std::string temps;
int bytelen = strByte.length() / 2;
unsigned int n;
for (int i = 0; i < bytelen; i++)
{
temps = strByte.substr(i * 2, 2);
FString sss = temps.c_str();
UE_LOG(LogTemp, Warning, TEXT("Show a String %s"), *sss);
sscanf(temps.c_str(), "%x", &n);
tc.Add(n);
}
return tc;
}
ab-----171
cd-----205