我有textField,用户输入任何文本,甚至不知道长度, 然后我必须将其转换为十六进制。我通过这段代码完成了它。
NSString * str = @"Hello World";
NSString * hexStr = [NSString stringWithFormat:@"%@",
[NSData dataWithBytes:[str cStringUsingEncoding:NSUTF8StringEncoding]
length:strlen([str cStringUsingEncoding:NSUTF8StringEncoding])]];
for(NSString * toRemove in [NSArray arrayWithObjects:@"<", @">", @" ", nil])
hexStr = [hexStr stringByReplacingOccurrencesOfString:toRemove withString:@""];
NSLog(@"%@", hexStr); 48656c6c6f20776f726c64
但是硬件从那开始。如何将每两个十六进制分隔为uint8_t。因为我不知道长度,但用户可以写任何长度的字符串,这将是巨大的十六进制。如果我知道我可以这样做的长度
NSMutableData *concatenate = [NSMutableData data];
uint8_t first=0x48;
uint8_t second = 0x56;
uint8_t third = 0x6c;
uint8_t fourth = 0x6f;
uint8_t fifth=0x20;
uint8_t sixth=0x77;
uint8_t seventh=0x6f;
uint8_t eighth=0x72;
uint8_t ninth=0x6c;
uint8_t tenth=0x64;
NSData* one = [NSData dataWithBytes:(void*)&first length:sizeof(first)];
NSData* two = [NSData dataWithBytes:(void*)&second length:sizeof(second)];
NSData* three = [NSData dataWithBytes:(void*)&third length:sizeof(third)];
NSData* four = [NSData dataWithBytes:(void*)&fourth length:sizeof(fourth)];
NSData* five = [NSData dataWithBytes:(void*)&fifth length:sizeof(fifth)];
NSData* six = [NSData dataWithBytes:(void*)&sixth length:sizeof(sixth)];
NSData* seven = [NSData dataWithBytes:(void*)&seventh length:sizeof(seventh)];
NSData* eight = [NSData dataWithBytes:(void*)&eighth length:sizeof(eighth)];
NSData* nine = [NSData dataWithBytes:(void*)&nineth length:sizeof(nineth)];
NSData* ten = [NSData dataWithBytes:(void*)&tenth length:sizeof(tenth)];
[concatenate appendData:one];
[concatenate appendData:two];
[concatenate appendData:three];
[concatenate appendData:four];
[concatenate appendData:five];
[concatenate appendData:six];
[concatenate appendData:seven];
[concatenate appendData:eight];
[concatenate appendData:nine];
[concatenate appendData:ten];
但是当我不知道长度时,我不知道。任何帮助或线索将受到高度赞赏。
答案 0 :(得分:1)
首次将NSString转换为NSData
NSString* str = @"Hello World";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
接下来,您将此数据发送到设备
[discoveredPeripheral writeValue:data forCharacteristic:charForValue type:CBCharacteristicWriteWithResponse];
您可以在这里发送带有设备响应的数据。当然,您的设备应准备好在有/无响应的情况下接收此类数据。
为了理解discoverPeripheral是您从
收到的变量-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
charForValue是
中收到的变量- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
提供必要的服务和特色。