我尝试编写一个将十六进制值字符串转换为Unicode UTF-8字符串的函数。当这个函数被调用一次,一切都很好。但是当函数连续两次使用相同或不同的参数调用时,两个输出字符串都没有意义。
void HEX2String(String* HEXstr, String* str) {
String s2 = "", s3 = "";
long c, c1, c0;
char ch[2] = { 0 };
for (int i = 0; i <= HEXstr->length() - 4; i = i + 4) {
s2 = HEXstr->substring(i, i + 1) + "x" + HEXstr->substring(i + 1, i + 4);
c = (hex2long(&s2));
if (c < 255)
*str += String((char)c);
else {
c1 = (128 + (c & B111111));
c0 = (192 + (c >> 6));
ch[1] = c1;
ch[0] = c0;
str->concat(ch);
}
}
}
String str1 = "0628064700200646062706450020062E062F0627000A0633064406270645000A064806310648062F0020062806470020063306CC0633062A06450020062A064806330637";
String str = "0628064700200646062706450020062E062F0627000A0633064406270645000A064806310648062F0020062806470020063306CC0633062A06450020062A064806330637000A00730061006C0061006D0020006200610072002000730068006F006D0061";
String msg = "";
void setup() {
Serial.begin(9600);
//First call
HEX2String(&str, &msg);
Serial.println(msg);
msg = "";
//Second call
HEX2String(&str1, &msg);
Serial.println(msg);
}
void main() {
//
}
如果我评论第二个电话,串口监听的输出是:
سلام
ورود به سیستم توسط
salam bar shoma
这是对的。如果未注释第二个调用,则串行监视器中的输出为:
ب⸮⸮ه⸮⸮ ن⸮⸮ا⸮⸮م⸮⸮ خ⸮⸮د⸮⸮ا⸮⸮
س⸮⸮ل⸮⸮ا⸮⸮م⸮⸮
و⸮⸮ر⸮⸮و⸮⸮د⸮⸮ ب⸮⸮ه⸮⸮ س⸮⸮ی⸮⸮س⸮⸮ت⸮⸮م⸮⸮ ت⸮⸮و⸮⸮س⸮⸮ط⸮⸮
salam bar shomaب⸮⸮ه⸮⸮ ن⸮⸮ا⸮⸮م⸮⸮ خ⸮⸮د⸮⸮ا⸮⸮
س⸮⸮ل⸮⸮ا⸮⸮م⸮⸮
و⸮⸮ر⸮⸮و⸮⸮د⸮⸮ ب⸮⸮ه⸮⸮ س⸮⸮ی⸮⸮س⸮⸮ت⸮⸮م⸮⸮ ت⸮⸮و⸮⸮س⸮⸮ط⸮⸮
答案 0 :(得分:2)
C-strings需要以null结尾。您的ch
不是。
将其定义为3个字符:
char ch[3] = { 0 };
并添加一个空终止符:
ch[0] = c0;
ch[1] = c1;
ch[2] = 0;