C++ hex string to byte array

谁都会走 提交于 2020-01-06 04:46:04

问题


I'm trying to send a string of hex values through 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

using UdpClient in C++.

What's the best way to convert string^ to  array< Byte >^ ?


回答1:


This works for me, although I haven't tested the error-detection all that well.

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;
    }
};



回答2:


If you're trying to send that as ascii bytes, then you probably want System::Text::Encoding::ASCII::GetBytes(String^).

If you want to convert the string to a bunch of bytes first (so first byte sent is 0x11), you'll want to split your string based on whitespace, call Convert::ToByte(String^, 16) on each, and put them into an array to send.



来源:https://stackoverflow.com/questions/6629534/c-hex-string-to-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!