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

主宰稳场 提交于 2019-12-06 14:21:45

问题


I am developing a device driver software for iOS and mac. In this I want to transfer a Number data in Binary form from my iPhone App to a device via blutoogh. Suppose I want to transfer a Data like 20 Jan 2013 10:30 am the i need to transfer 200120131030 in a binary sequence. means first binary of 20 then binary of 01 then binary of 2013 and so on... other device is not running on iOS. I convert this number to NSData but can't understand that NSData is abinary data or not. Is there a way to make it binary and transfer it. (I can transferred data via bluetooth)


回答1:


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.



来源:https://stackoverflow.com/questions/14406063/how-to-transfer-a-data-in-binary-form-via-bluetooth-in-iphone-app

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