簡體   English   中英

如何將CString轉換為BYTE?

[英]How do I convert a CString to a BYTE?

我的程序中有CStrings,其中包含BYTE信息,如下所示:

L"0x45"

我想將其轉換為值為0x45的BYTE類型。 我該怎么做呢? 我可以找到的所有示例都試圖獲取字符串本身的字面值,但是我想獲取CString中包含的值並將THAT轉換為BYTE。 我該如何實現?

您可以使用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::GetString() 顯式獲取CString實例的const wchar_t*指針。 ,或使用static_cast<const wchar_t*>(str)
然后,將構建一個臨時的std::wstring傳遞給std::stoi()進行轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM