user3330644
user3330644

Reputation: 433

How do I convert a CString to a BYTE?

I have CStrings in my program that contain BYTE information like the following:

L"0x45"

I want to turn this into a BYTE type with value 0x45. 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. How do I achieve this?

Upvotes: 1

Views: 821

Answers (1)

Mr.C64
Mr.C64

Reputation: 42964

You can use the wcstoul() conversion function, specifying base 16.

e.g.:

#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():

#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).
Then, a temporary std::wstring will be built to be passed to std::stoi() for the conversion.

Upvotes: 2

Related Questions