C ++十六进制字符串到字节数组 [英] C++ hex string to byte array

查看:177
本文介绍了C ++十六进制字符串到字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过udp发送一个十六进制值字符串,

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

使用UdpClient

using UdpClient in C++.

string ^ 转换为数组的最佳方式是< Byte> ^

推荐答案

这对我有用,虽然我没有测试错误 - 检测所有这一切。

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

这篇关于C ++十六进制字符串到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆