我正在使用Asyncsocket通过TCP发送字节。我有代码工作,但是当发送字节0xF8时,我遇到了问题。
以下是我尝试过的(在下面的评论中)和代码:
NSString *ip_current = self.text_ip.text;
sockethost=ip_current;
socketport=9100;
[self connect];
//a working one as long as I don't use 0xF8
NSData *dataStream = [[NSString stringWithFormat:@"%c%c",0x1d,0x31] dataUsingEncoding:NSUTF8StringEncoding];
[self.socket writeData:dataStream withTimeout:1 tag:1];
//This one below will give 0x1d, 0xc3,0xb8 (After some research I found that this is due to encoding issue with UTF8)
NSData *dataStream = [[NSString stringWithFormat:@"%c%c", 0x1d, 0xf8 dataUsingEncoding:NSUTF8StringEncoding];
//People suggest that using ASCII encoding, this time I don't get 3 bytes but 2 bytes with wrong data with 1d and 6f(f8 change to 6f)
NSData *dataStream = [[NSString stringWithFormat:@"%c%c%c",0x1d,0xf8,0x31] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[self.socket disconnectAfterWriting];
所以,无论我使用什么编码,都有问题。有人知道如何解决这个问题吗?在此先感谢!!!
答案 0 :(得分:1)
你只想要一个字节。字符串与此无关。从字节创建NSData
,而不是字符串。
uint8_t byte = 0xF8;
NSData *dataStream = [NSData dataWithBytes:&byte length:1];