0

So I have this data packet that I want to send it to my device using TCP/IP protocol. My array is:

unsigned char array1[] = {'0x00', '0x84', '0x00', '0x00', '0x00', '0x06', '0x54', '0x01', '0x00', '0x01', '0x00', '0x03'};

I want this to convert into a string. How do I do it?

Right now I am just manually writing down the decimal equivalent:

unsigned char array1[] = {0,132,0,0,0,6,84,5,0,2,255,0};

and converting it into string:

std::string data ( array1, array1 + sizeof array1 / sizeof array1[0] );

However, I wonder can I use my hex packet just like a string directly?

string x= "00 84 00 00 00 06 54 05 00 02 FF 00";

Also is there a way I can design my message header which is the first 7 bytes that dont change? What changes is the rest of the part?

5
  • 1
    Note that '0x00' is not really a single "character", it's a multi-byte character literal. Perhaps you mean e.g. unsigned char array1[] = {0x00, 0x84, ... };? Without the quotes? Commented Apr 19, 2017 at 7:20
  • Without the quotes, it throws warning for unsigned type. Commented Apr 19, 2017 at 7:22
  • Why exactly do you want it as std::string? I am not quite sure that this is the "correct" data type... Commented Apr 19, 2017 at 7:24
  • Because my class that I am inheriting, has the function to send this packet over the tcp network. The function only supports string. hence I need to convert my data into string. Commented Apr 19, 2017 at 7:25
  • @ArunavaNag The question is much clearer now! Commented Apr 19, 2017 at 8:05

1 Answer 1

1

The following code should do what you need.

std::string s { "\x00\x01\x02\x03\x04", 5 };

Use the std::string constructor that also takes the length aka number of bytes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.