我如何将CString转换为BYTE
How do I convert a CString to a BYTE?
我的程序中有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()
进行转换。
相关文章:
- C++如何将字符数组转换为字节向量(向量<byte>)
- 为什么从 char 转换为 std::byte 可能是未定义的行为?
- C++ 无法将 std::vector<BYTE> 转换为字符串或字符数组
- 三维数组中的C/C++DWORD到BYTE和BYTE到DWORD的转换
- 在 C++ 中转换 std::string,使其可以是 C# 中的 byte[]
- 将 BYTE 数组转换为无符号长整型
- 将 BYTE* 从MODULEENTRY32的 modBaseAddr 转换为 std::string
- 如何在不产生 JNI 问题的情况下转换 byte[] -> uint8_t[]?
- C++ 如何将 BYTE* 转换为 _CERT_TEMPLATE_EXT* 并在进一步使用前检查结果
- 将 BSTR 转换为 BYTE 数组C++
- 如何将 ArrayList<byte[]> 转换为 JNI 的 vector<char[]>?
- 字符串迭代器不兼容错误,当我将字符串转换为矢量<byte>时
- Visual C++ 2010 - 转换 10 GB BYTE 数组的最快方法?
- 如何将 BYTE 数组转换为字符数组以使用套接字 C++ 发送
- 在 VSS 硬件框架 c++ 中将 BYTE 转换为 BSTR
- 正在将托管Byte数组转换为非托管字符串
- 需要将cstring转换为byte*,并需要在c++函数中将其作为i/p参数传递
- 无法从'byte[]'转换为'byte*'
- Qt & Kinect:如何将 BYTE* pBuffer 转换为 QByteArray 或 const uchar*?
- 将BYTE*转换为wstring