How to transfer a data in Binary form via Bluetooth in iPhone App

蓝咒 提交于 2019-12-04 18:22:56

Let's say you decide to represent the date as a string of 12 digits, or 12 bytes. You can get NSData this way:

NSDate *date = // the date you start with

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"ddMMYYYYHHmm"];
NSString *dateString = [formatter stringFromDate:date];

// dateString can be any string you wish to send.  In this example, it represents a date
NSData *data = [dateString dataUsingEncoding:NSUTF8StringEncoding];

You can get a pointer to the byte data with the bytes selector on NSData. Say you want to copy out the data:

NSUInteger length = [data length];
char *buffer = (char *)malloc(length);
memcpy(buffer, [data bytes], length);

As I mentioned in my comment, a more compact serialization is a long integer. You can get smaller data like this:

unsigned long dateInt = [dateString intValue];
NSData *data = [NSData dataWithBytes:&dateInt length:sizeof(dateInt)];

... then get the bytes out the same way. The important thing to remember is that the sender and receiver of these bytes must agree on how to interpret them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!