简体   繁体   English

如何将CString转换为BYTE?

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

I have CStrings in my program that contain BYTE information like the following: 我的程序中有CStrings,其中包含BYTE信息,如下所示:

L"0x45"

I want to turn this into a BYTE type with value 0x45 . 我想将其转换为值为0x45的BYTE类型。 How do I do this? 我该怎么做呢? All examples I can find are trying to get the literal byte value of the string itself, but I want to take the value contained within the CString and convert THAT to a BYTE. 我可以找到的所有示例都试图获取字符串本身的字面值,但是我想获取CString中包含的值并将THAT转换为BYTE。 How do I achieve this? 我该如何实现?

You can use the wcstoul() conversion function, specifying base 16. 您可以使用wcstoul()转换函数,指定基数为16。

eg: 例如:

#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 

Output: 输出:

 69 

As an alternative, you can also consider using new C++11's std::stoi() : 或者,您也可以考虑使用新的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;
}

NOTE 注意
In this case, since std::stoi() expects a const std::wstring& argument, you must explicitly get the const wchar_t* pointer for the CString instance, either using CString::GetString() as I did (and I prefer), or using static_cast<const wchar_t*>(str) . 在这种情况下,由于std::stoi()需要一个const std::wstring&参数,因此您必须像我一样(并且我更喜欢使用CString::GetString() 显式获取CString实例的const wchar_t*指针。 ,或使用static_cast<const wchar_t*>(str)
Then, a temporary std::wstring will be built to be passed to std::stoi() for the conversion. 然后,将构建一个临时的std::wstring传递给std::stoi()进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM