about \x00 string will interrupt the sring

I want to send a string like "\x01\x03\x04\x01\x00\xC1\x94" from arduino to PC,but i find it will become""\x01\x03\x04\x01\". The string will interrupt on \x00. Why it happen? and how to solve?

String s="\x01\x03\x04\x01\x00\xC1\x94"; Serial.println(s);

I'm surprised it gets to "\x00".

Try this:-

String s = "\\x01\\x03\\x04\\x01\\x00\\xC1\\x94";

It's really better to avoid the String class, by the way, and use C strings, (char arrays). The String class is resource heavy and can lead to memory fragmentation.

A backslash in C++ is used to signify an 'escape sequence', like '\n', '\t' etc.

To include an actual backslash in a string, it must itself be an escape sequence. More info here, including a chart of escape sequences:- https://msdn.microsoft.com/en-us/library/6aw8xdf2.aspx

Here's a better chart, (non-Microsoft-specific):- http://en.cppreference.com/w/cpp/language/escape

I don't think he wants backslashes; it wants to output small ascii values. I didn't know that "\x01" was legal, but it makes sense. If so, "\x00" is a null, which terminates C-style strings for the purposes of most string function calls (like Serial.print()) (Hmm. I don't know if it's legal in capital-S strings, but presumably even if so, it wouldn't get put in the string in the first place.) If you want to output nulls, you'll need to use the buffer-oriented version, or write the null separately:

char s[]="\x01\x03\x04\x01\x00\xC1\x94";
Serial.write(s, sizeof(s));

westfw: I don't think he wants backslashes; it wants to output small ascii values.

I misunderstood, and thought he was sending to the serial monitor. My bad - he did say "from arduino to PC" and not "from Arduino to serial monitor".

Now it makes sense that \x00 ends his string. Ha already is using escape sequences.:-

\xnn arbitrary hexadecimal value byte nn

Thank you very much.

I used :

char s[]="\x01\x03\x04\x01\x00\xC1\x94"; Serial.write(s, sizeof(s));

it worked, but it return "x01\x03\x04\x01\x00\xC1\x94\x00". So I need change the code to:

Serial.write(s, sizeof(s)-1);

But I don't know why...

Double quotes cause a string-terminating null to be added. (Oops, sorry.)