2

My input is

char *str = "/send 13 01 09 00"; 

I need the output as just

BYTE* result = { 0x13, 0x09, 0x00 }; 

(so skipping the /send)

Can somebody provide me a solution to get bytes from a string of hex bytes?

This is what I've tried:

#include "stdafx.h" #include <iostream> #include <windows.h> #include <conio.h> #include <string> byte *ToPacket(const char* str) { const char *pos = str; unsigned char val[sizeof(str)/sizeof(str[0])]; size_t count = 0; for(count = 0; count < sizeof(val)/sizeof(val[0]); count++) { sscanf_s(pos, "%2hhx", &val[count]); pos += 2 * sizeof(char); } return val; } int _tmain(int argc, _TCHAR* argv[]) { redo: while (true) { std::string key; std::getline(std::cin, key); if (key != "") { if (key == "/hit") { BYTE packet[] = { 0x13, 0x01, 0x00 }; int size = sizeof(packet) / sizeof(packet[0]); std::cout << "[FatBoy][" << key << "]: Hit\n"; } else if (strstr(key.c_str(), "/send")) { BYTE * packet = ToPacket(key.c_str()); int size = sizeof(packet) / sizeof(packet[0]); } key = ""; break; } Sleep(100); } goto redo; } 
3
  • I edited post with what I tried, the byte *ToPacket function dosent provide me the result I want Commented Dec 18, 2012 at 22:21
  • 2
    You want the output to be BYTE* result = { 0x13, 0x01 0x09, 0x00 }; right? Commented Dec 18, 2012 at 22:21
  • Yeah, I need a function that will give me the bytes of anything I type after /send XX XX XX XX XX ... Commented Dec 18, 2012 at 22:22

2 Answers 2

2
#include <iostream> #include <sstream> #include <string> #include <iomanip> std::string s("/send 13 01 09 00"); int v1,v2,v3,v4; std::string cmd; std::istringstream inp_stream(s); inp_stream >> cmd >> std::setbase(16) >> v1 >> v2 >> v3 >> v4; 
Sign up to request clarification or add additional context in comments.

Comments

2

Use std::istringstream with std::hex IO manipulator to populate a std::vector<unsigned char>:

std::string s("13 01 09 00"); std::vector<unsigned char> v; std::istringstream in(s); in >> std::hex; unsigned short c; while (in >> c) v.push_back(static_cast<unsigned char>(c)); 

See demo at http://ideone.com/HTJmzJ .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.