【问题标题】:C++ hex string to byte arrayC++ 十六进制字符串到字节数组
【发布时间】:2011-10-01 13:17:11
【问题描述】:

我正在尝试通过 udp 发送一串十六进制值,

11 22 33 44 37 4D 58 33 38 4C 30 39 47 35 35 34 31 35 31 04 D7 52 FF 0F 03 43 2D AA

在 C++ 中使用 UdpClient。

string^ 转换为 array< Byte >^ 的最佳方法是什么?

【问题讨论】:

标签: .net string c++-cli bytearray hex


【解决方案1】:

如果您尝试将其作为 ascii 字节发送,那么您可能需要System::Text::Encoding::ASCII::GetBytes(String^)

如果您想先将字符串转换为一堆字节(因此发送的第一个字节是 0x11),您需要根据空格分割字符串,在每个字符串上调用 Convert::ToByte(String^, 16),然后将它们放入数组中发送。

【讨论】:

  • 虽然将 C# 转换为 C++/CLI 很容易,但它并不像在每种类型的末尾标记 ^ 那样简单。
  • 已修复,除了没有实际编译检查。
  • System::String 有一个大写的 S。小写的 string 是一个 C# 关键字,也是一个原生 C++ 类型 std::string,但绝不表示 .NET 字符串。 (是的,我知道这个问题也弄错了。)
【解决方案2】:

这对我有用,虽然我还没有很好地测试错误检测。

ref class Blob
{
    static short* lut;
    static Blob()
    {
        lut = new short['f']();
        for( char c = 0; c < 10; c++ ) lut['0'+c] = 1+c;
        for( char c = 0; c < 6; c++ ) lut['a'+c] = lut['A'+c] = 11+c;
    }
public:
    static bool TryParse(System::String^ s, array<System::Byte>^% arr)
    {
        array<System::Byte>^ results = gcnew array<System::Byte>(s->Length/2);
        int index = 0;
        int accum = 0;
        bool accumReady = false;
        for each (System::Char c in s) {
            if (c == ' ') {
                if (accumReady) {
                    if (accum & ~0xFF) return false;
                    results[index++] = accum;
                    accum = 0;
                }
                accumReady = false;
                continue;
            }
            accum <<= 4;
            accum |= (c <= 'f')? lut[c]-1: -1;
            accumReady = true;
        }
        if (accumReady) {
            if (accum & ~0x00FF) return false;
            results[index++] = accum;
        }
        arr = gcnew array<System::Byte>(index);
        System::Array::Copy(results, arr, index);
        return true;
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 2013-10-13
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多