使用 NSData *_data = [hexString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableString *_string = [NSMutableString stringWithString:@""];
for (int i = 0; i < _data.length; i++) {
unsigned char _byte;
[_data getBytes:&_byte range:NSMakeRange(i, 1)];
if (_byte >= 32 && _byte < 127) {
[_string appendFormat:@"%c", _byte];
} else {
[_string appendFormat:@"[%d]", _byte];
}
}
asciiString = _string; // Still shows the same as before..
功能时遇到此问题。我想连接多个字符串。
我有一个结构snprintf()
定义为
msg
使用这些值:
struct timerMessage {
char txncode[4];
char date[8];
char time[6];
char mac[16];
char userid[32];
char instid[9];
char merchcode[2];
char seqno[3];
char data[100];
} msg;
这就是我将字符串连接起来的方式:
{txncode = "9902", date = "08082015", time = "172936", mac = ' ' <repeats 16 times>,
userid = ' ' <repeats 32 times>, instid = " ", merchcode = " ", seqno = "001",
data = "FILE1TEST11|1P", '\000' <repeats 85 times>}
更新:MCVE
struct msg
snprintf(msgbuffer,sizeof(msgbuffer),"%s%s%s%s%s%s%s%s%s",msg.txncode,
msg.date,msg.time,msg.mac,msg.userid,msg.instid,msg.merchcode,msg.seqno,msg.data);
VAR
char txncode[4] ,date[8], time[6], mac[16], userid[32], instid[9], merchcode[2], seqno[3], data[100];
连接的结果:
sprintf(msg.txncode, "%s","9901");
sprintf(msg.date, "%002d%002d%002d",month,day,year);
sprintf(msg.time, "%002d%002d%002d",hr,min,sec);
sprintf(msg.mac, "% 16s", " ");
sprintf(msg.userid, "% 32s", " ");
sprintf(msg.instid, "% 9s", " ");
sprintf(msg.merchcode,"% 2s", " ");
sprintf(msg.seqno,"%003d",1);
snprintf(msg.data,sizeof(msg.data),"%s|%s","FILE1TEST11","1P");
结果应该是:
"990208082015172936", ' ' (repeats 59 times), "001FILE1TEST11|1P0808"
答案 0 :(得分:1)
这里只有一个问题。在所有字符数组中,您使用值填充所有可用位置,并且任何位置都不能包含NULL ('/0')
字符。通过在每个字符数组中添加一个字符来修改您的结构,如下所示,您将获得所需的结果。
3 struct timerMessage {
4 char txncode[5];
5 char date[9];
6 char time[7];
7 char mac[17];
8 char userid[33];
9 char instid[10];
10 char merchcode[3];
11 char seqno[4];
12 char data[100];
13 } msg;