我如何将CString转换为BYTE

How do I convert a CString to a BYTE?

本文关键字:转换 BYTE CString      更新时间:2023-10-16

我的程序中有cstring,其中包含如下字节信息:

L"0x45"

我想把它变成一个值为0x45的BYTE类型。我该怎么做呢?我能找到的所有例子都试图获得字符串本身的字面值字节值,但我想取CString中包含的值并将其转换为字节。我该如何做到这一点?

您可以使用 wcstoul() 转换函数,指定进制16。

例如:

#define UNICODE
#define _UNICODE
#include <stdlib.h> // for wcstoul()
#include <iostream> // for console output
#include <atlstr.h> // for CString
int main() 
{
    CString str = L"0x45";
    static const int kBase = 16;    // Convert using base 16 (hex)
    unsigned long ul = wcstoul(str, nullptr, kBase);
    BYTE b = static_cast<BYTE>(ul);
    std::cout << static_cast<unsigned long>(b) << std::endl;
}
C:Temp>cl /EHsc /W4 /nologo test.cpp
输出:

69

作为替代方案,您还可以考虑使用新的c++ 11的 std::stoi() :

#define UNICODE
#define _UNICODE
#include <iostream> // for console output
#include <string>   // for std::stoi()
#include <atlstr.h> // for CString
int main() 
{
    CString str = L"0x45";
    static const int kBase = 16;    // Convert using base 16 (hex)
    int n = std::stoi(str.GetString(), nullptr, kBase);
    BYTE b = static_cast<BYTE>(n);
    std::cout << static_cast<unsigned long>(b) << std::endl;
}

注意
在这种情况下,由于std::stoi()期望const std::wstring&参数,您必须显式获取CString实例的const wchar_t*指针,要么像我一样使用CString::GetString()(并且我更喜欢),要么使用static_cast<const wchar_t*>(str)。然后,一个临时std::wstring将被传递给std::stoi()进行转换。