The binary conversion in iOS bluetooth

Source: Internet
Author: User

Recently busy a Bluetooth project, in the processing of Bluetooth data, often encountered between the conversion between the system, Bluetooth processing is 16 binary (NSData), and we used to count the way is 10, in order to save space, Bluetooth will be 16 binary (NSData) split into 2 binary records. Here we look at how to convert between them.

Suppose we want to send 0x1b9901 this data to Bluetooth

byte Turn NSData
Byte value[3]={0};value[0]=0x1B;value[1]=0x99;value[2]=0x01;NSData * data = [NSData dataWithBytes:&value length:sizeof(value)];//发送数据[self.peripheral writeValue:data forCharacteristic:self.write type:CBCharacteristicWriteWithoutResponse];
    • Advantages: This method is relatively simple, no conversion, directly a byte of a byte of the assembly to send out.
    • Cons: It can be cumbersome and difficult to change when sending data for long periods of time.
NSString Turn NSData
- (NSData *) Hextobytes: (NSString *) str{nsmutabledata* data = [Nsmutabledata data];int idx;for (idx =0; idx+2 <= Str. length; idx+=2) {nsrange range = nsmakerange (IDX, 2); nsstring* hexstr = [str substringwithrange:range]; nsscanner* scanner = [nsscanner scannerwithstring:hexstr]; unsigned int intvalue; [Scanner scanhexint:&intvalue]; [Data appendbytes:&intvalue length:1];} return data;} //send data [self.peripheral Writevalue:[self hextobytes:@ "1B9901"] forCharacteristic:< Span class= "Hljs-keyword" >self.write type:cbcharacteristicwritewithoutresponse];  
    • Advantages: More intuitive, you can convert a strip of data at a time, for some simple Bluetooth programs, this conversion can handle most of the situation.
    • Cons: Only some fixed instructions can be sent and cannot participate in the calculation.
Seek checksums and

The next step is to discuss what data is sent and what needs to be calculated.
The most common scenario for sending data to be computed is the checksum (CHECKSUM). This is based on the hardware vendor, the common rules for verifying and checking are:

    • If the send data length is n bytes, the checksum is the lower byte of the sum of the preceding n-1 bytes
    • Checksum=0x100-checksum (checksum of the previous step)

If I want to send a 0x1b9901 with Colonel's test, the method is:

-(NSData *) Getchecksum: (NSString *) bytestr{int length = (int) bytestr.length/2; NSData *data = [self hextobytes:bytestr]; Byte *bytes = (Unsignedchar *) [data bytes]; Byte sum =0;for (int i =0; i<length; i++) {sum + = bytes[i];}int sumT = SUM;int at =256-SUMT;printf"Checksum:%d\n", at);if (at = =() {at =0;} NSString *str = [NSString stringwithformat:@"%@%@", Bytestr,[self Tohex:at]];return [self hextobytes:str];}Convert decimal to hexadecimal-(NSString *) Tohex: (int) tmpid{nsstring *nlettervalue; NSString *str [email protected]"";int ttmpig;for (int i =0; i<9; i++) {ttmpig=tmpid%16; Tmpid=tmpid/16;Switch (ttmpig) {Case10:nlettervalue [email protected]"A";BreakCase11:nlettervalue [email protected]"B";BreakCase12:nlettervalue [email protected]"C";BreakCase13:nlettervalue [email protected]"D";BreakCase14:nlettervalue [email protected]"E";BreakCase15:nlettervalue [email protected]"F";Break ; default:nlettervalue = [NSString stringwithformat:@"%u", Ttmpig];} str = [Nlettervalue stringbyappendingstring : STR]; if (tmpid = = 0) {break ;}} //Not enough one byte to gather 0if (str.length = = 1) { return [nsstring stringwithformat:@"0%@", str];} else{ return str;}} //Send data NSData *data = [self getchecksum:@"1b9901"];  Data=<1b99014b>[self.peripheral writevalue:data forCharacteristic:self.write Type: Cbcharacteristicwritewithoutresponse];               
Splitting data

This is more troublesome, for a chestnut: in the transmission of a piece of information, I want to put time in, not with time stamp, but also to save space, so there is a new way to store time.
Here are some additional C language knowledge:

    • 8 bits (bit) of one byte
    • Char 1 byte int 4 byte unsigned 2 bytes float 4 bytes

The conditions for storing time are:

    • Use only four bytes (32 bits)
    • The first 5 digits represent the year (starting from 2000), followed by 4 digits for the month, then 5 for the day, then 5 for the time, then 6 for the minute, then 3 for the week, and the remaining 4 bits reserved.

Such an intuitive solution is to remove the current time of the month and day of the week, first turned into 2, and then turned into 16 into the system sent out. Of course, you write in this, you should read the 16 binary data first into 2 and then into the 10 binary display. We will follow this simple and rough idea, the preparation of work as follows:

10-in-Turn 2-in system
Decimal Turn Binary-(NSString *) Tobinarysystemwithdecimalsystem: (int) num Length: (int) length{int remainder =0;Remainderint divisor =0;Divisor NSString * Prepare = @"";while (true) {remainder = num%2; divisor = num/2; num = divisor; prepare = [Prepare Stringbyappendingformat:@ "%d ", remainder]; if (divisor = 0) {break;}} //Reverse output NSString * result = @int i = length-1; I >= 0; i--) { if (i <= prepare.length-1) {result = [result] Stringbyappendingformat:@ "%@", [Prepare Substringwithrange:nsmakerange (i, 1)]; }else{result = [result stringbyappendingstring:@return result;}            
2-in-turn 10-in system
//  二进制转十进制- (NSString *)toDecimalWithBinary:(NSString *)binary{int ll = 0 ;int  temp = 0 ;for (int i = 0; i < binary.length; i ++){ temp = [[binary substringWithRange:NSMakeRange(i, 1)] intValue]; temp = temp * powf(2, binary.length - i - 1); ll += temp;}NSString * result = [NSString stringWithFormat:@"%d",ll];return result;}
16-binary and 2-in-binary mutual transfer
-(NSString *) Getbinarybyhex: (NSString *) hex binary: (NSString *) binary{nsmutabledictionary *hexdic = [[ Nsmutabledictionary alloc] Init];hexdic = [[Nsmutabledictionary alloc] Initwithcapacity:16]; [Hexdicsetobject:@"0000"forkey:@"0"]; [Hexdicsetobject:@"0001"forkey:@"1"]; [Hexdicsetobject:@"0010"forkey:@"2"]; [Hexdicsetobject:@"0011"forkey:@"3"]; [Hexdicsetobject:@"0100"forkey:@"4"]; [Hexdicsetobject:@"0101"forkey:@"5"]; [Hexdicsetobject:@"0110"forkey:@"6"]; [Hexdicsetobject:@"0111"forkey:@"7"]; [Hexdicsetobject:@"1000"forkey:@"8"]; [Hexdicsetobject:@"1001"forkey:@"9"]; [Hexdicsetobject:@"1010"forkey:@"A"]; [Hexdicsetobject:@"1011"forkey:@"B"]; [Hexdicsetobject:@"1100"forkey:@"C"]; [Hexdicsetobject:@"1101"forkey:@"D"]; [Hexdicsetobject:@"1110"forkey:@"E"]; [Hexdicsetobject:@"1111"forkey:@"F"]; Nsmutablestring *binarystring=[[nsmutablestring alloc] init];if (hex.length) {for (int i=0; I<[hex length]; i++) {Nsrange rage; rage.length = 1; rage.location = i; NSString *key = [Hex substringwithrange:rage]; [Binarystring Appendstring:hexdic[key]]; }}else{for (int i=0; i< Binary.length; I+=4) {nsstring *substr = [Binary Substringwithrange:nsmakerange (i, 4)]; int index = 0; for (nsstring *str in hexdic.allvalues) {index + +; if ([subStr isequaltostring:str]) {[binarystring Appendstring:hexdic.allkeys[index-1]"; break;} }}}return binarystring;}          

With these kinds of conversion functions, the completion of the above function is much easier, how to operate here do not write one by one out. But always feel strange, such a small function how to write such a lot of code, of course, you can use the C language method to solve. Here is mainly to show how the data in iOS conversion, C language implementation method here is not written, interested students can study under.

Two + functions included

int turn NSData

- (NSData *) setId:(int)Id {//用4个字节接收Byte bytes[4];bytes[0] = (Byte)(Id>>24);bytes[1] = (Byte)(Id>>16);bytes[2] = (Byte)(Id>>8);bytes[3] = (Byte)(Id);NSData *data = [NSData dataWithBytes:bytes length:4];}

NSData ext. int
The data that is received0x00000a0122

An int that represents 4 bytesNSData *intdata = [Data subdatawithrange:Nsmakerange (2,4)];int value =Cfswapint32bigtohost (* (int*) ([intdata bytes]); //655650//2 bytes represented IntNSData * Intdata = [Data subdatawithrange:nsmakerange (4, 2)]; int value = cfswapint16bigtohost (* ( int*) ([intdata bytes]); //290//1 bytes represent Intchar *bs = ( Span class= "Hljs-keyword" >unsigned char *) [[Data subdatawithrange: nsmakerange (5, 1)] Bytes];int value = *bs; //34             

These two transformations in some scenarios use frequency is also very high, Bluetooth inside the data conversion is basically so much, I hope to help everyone.
For more on byte coding, you can click here: Portal

Extended

Connection BLE4.0 based on CoreBluetooth4.0 framework demo: Don't you want to order?



Wen/Yong Chuang-the Horizon Jasmine Tea (Jane book author)
Original link: http://www.jianshu.com/p/a5e25206df39
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

The binary conversion in iOS bluetooth

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.