1. 程式人生 > >IOS 藍芽通訊各種資料型別之間的轉換

IOS 藍芽通訊各種資料型別之間的轉換

在與藍芽互動開發的過程中 涉及到各種資料型別的轉換,這裡寫了一個轉換類:

/*********************************************************************************

                 **         資料型別轉換工具類        **

                 **  *    *            *           **

                 **   *  *             *           **

                 **    *               *           **

                 **    *               *           **

                 **    *               *******     **

 ********************************************************************************/

#import <Foundation/Foundation.h>

@interface YDataCoverTool : NSObject

/**  Hex  表示十六進位制 **/

/**

 *   NSString 字串轉化為 16 進位制字串  @"abcde" --> @"0a1234 0b23454"

 */

+(NSString*)coverFromStringToHexStr:(NSString*)string;

/**

 *  16 進位制字串轉化為 NString 字串  @"0a1234 0b23454" -- > @"abcde"

 */

+(NSString*)coverFromHexStringToStr:(NSString*)hexStr;

/**

 *  16 進位制字串轉化為 NSData   此處注意的是: 傳入的字串轉為

128字元不足位的補了數字如果需要對應位擷取位置即可   @"0a1234 0b23454" -- > <0a1234 0b23454>

 */

+(NSData*)coverFromHexStrToData:(NSString*)hexStr;

/**

 *   將字串轉化為對應的  ASCII 字串

 */

+(NSString*)coverFromStringToAsciiStr:(NSString*)string;

/**

 *  將字串8個字元之後新增空格

 */

+(NSString *)stringAppendSpace:(NSString *)string;

/**

 *  16 進位制 NSData 轉化為 NSString 字串  <0a1234 0b23454> --> @"0a1234 0b23454"

 */

+(NSString*)coverFromHexDataToStr:(NSData*)hexData;

/**

 *  NSString  轉化為 NSData @"abcde" --> <0a1234 0b23454>

 */

+(NSData*)coverFromStringToHexData:(NSString*)string;

/**

 *  NSData 轉化為  16進位制字串   <0x00adcc asdfgwerf asdddffdfd> --> @"0x00adccasdfgwerfasdddffdfd"

 */

+(NSString*)coverFromDataToHexStr:(NSData*)data;

/**

 *  byte 陣列 -- > NSData  Byte bytes[] --> <0a1234 0b23454>

 */

+(void)coverFromBytesArrToData;

/**

 *  byte 陣列 -- > 16 進位制字串 Byte bytes[] --> @"0a1234 0b23454"

 */

+(void)coverFromBytesArrToHexStr;

/**

 *  16 進位制字串 -- > 10 進位制數字   @"0F" --> 15   @"10" -- > 16

 */

+(UInt64)coverFromHexStrToInt:(NSString*)hexStr;

/**

 *  10進位制  --- > 16 進位制字串  15 ---> @"0F"

 */

+(NSString*)coverFromIntToHex:(NSInteger)tmpid;

/**

 *  int 型別 --> NSData 4 個位元組接收

 */

+(NSData *) setId:(int)Id;

/**

 *  NSData  --> int  4 個位元組接收表示

 */

+(int) setDa:(NSData*)intData;

/**

 *  將時間戳 int ---> 4 個位元組的 Data 資料

 */

+(NSData*) coverToByteWithData:(int)timeInterval;

@end

#import "YDataCoverTool.h"

@implementation YDataCoverTool

+(NSString*)coverFromStringToHexStr:(NSString*)string

{

NSString * hexStr = [NSStringstringWithFormat:@"%@",

                         [NSDatadataWithBytes:[string cStringUsingEncoding:NSUTF8StringEncoding]

length:strlen([string cStringUsingEncoding:NSUTF8StringEncoding])]];

for(NSString * toRemove in [NSArrayarrayWithObjects:@"<", @">", nil])

        hexStr = [hexStr stringByReplacingOccurrencesOfString:toRemove withString:@""];

return hexStr;

}

+(NSString*)coverFromHexStringToStr:(NSString*)hexStr

{

if (([hexStr length] % 2) != 0)

returnnil;

NSMutableString *string = [NSMutableStringstring];

for (NSInteger i = 0; i < [hexStr length]; i += 2) {

NSString *hex = [hexStr substringWithRange:NSMakeRange(i, 2)];

NSInteger decimalValue = 0;

sscanf([hex UTF8String], "%x", &decimalValue);

        [string appendFormat:@"%c", decimalValue];

    }

return string;

}

//  eg NSString *hexString = @"3e435fab9c34891f"; //16進位制字串

+(NSData*)coverFromHexStrToData:(NSString*)hexString

{

int j=0;

Byte bytes[128];  ///3ds keyByte 陣列, 128

for(int i=0;i<[hexString length];i++)

    {

int int_ch;  /// 兩位16進位制數轉化後的10進位制數

unichar hex_char1 = [hexString characterAtIndex:i]; ////兩位16進位制數中的第一位(高位*16)

int int_ch1;

if(hex_char1 >= '0' && hex_char1 <='9')

            int_ch1 = (hex_char1-48)*16;   //// 0 Ascll - 48

elseif(hex_char1 >= 'A' && hex_char1 <='F')

            int_ch1 = (hex_char1-55)*16; //// A Ascll - 65

else

            int_ch1 = (hex_char1-87)*16; //// a Ascll - 97

        i++;

unichar hex_char2 = [hexString characterAtIndex:i]; ///兩位16進位制數中的第二位(低位)

int int_ch2;

if(hex_char2 >= '0' && hex_char2 <='9')

            int_ch2 = (hex_char2-48); //// 0 Ascll - 48

elseif(hex_char1 >= 'A' && hex_char1 <='F')

            int_ch2 = hex_char2-55; //// A Ascll - 65

else

            int_ch2 = hex_char2-87; //// a Ascll - 97

        int_ch = int_ch1+int_ch2;

NSLog(@"int_ch=%d",int_ch);

        bytes[j] = int_ch;  ///將轉化後的數放入Byte數組裡

        j++;

    }

return [[NSDataalloc] initWithBytes:bytes length:128];

}

+(NSString*)coverFromStringToAsciiStr:(NSString*)string

{

NSString *str = @"123456789ABCDEFG";

constchar *s = [str cStringUsingEncoding:NSASCIIStringEncoding];

size_t len = strlen(s);

NSMutableString *asciiCodes = [NSMutableStringstring];

for (int i = 0; i < len; i++) {

        [asciiCodes appendFormat:@"%02x ", (int)s[i]];

    }

return asciiCodes;

}

+(NSString *)stringAppendSpace:(NSString *)string

{

if(![string isEqualToString:@""])

    {

NSMutableString *spaceString = [[NSMutableStringalloc]init];

if(string.length > 8//字串個數大於8

        {

NSMutableArray *spaceIndexs = [NSMutableArraynew];

for (int index = 0; index < string.length; index++) {

NSString *tmpStr = [string substringWithRange:NSMakeRange(index, 1)];

if ([tmpStr isEqualToString:@" "]) {

                    [spaceIndexs addObject:[NSNumbernumberWithInt:index]];

                }

            }

int lastIndex = (int)[[spaceIndexs lastObject] integerValue]+1;

            [spaceString appendString:[string substringWithRange:NSMakeRange(0, lastIndex)]];

NSMutableString   *newStr =[NSMutableStringstringWithString:[string substringFromIndex:lastIndex]];

if(newStr.length == 8)

            {

                [newStr appendString:@" "];

            }

            [spaceString appendString:newStr];

return spaceString;

        }elseif(string.length == 8){  //字串個數為8時,新增空格

            [spaceString appendString:string];

            [spaceString appendString:@" "];

return spaceString;

        }

    }

return  string;

}

+(NSString*)coverFromHexDataToStr:(NSData*)hexData

{

NSString* result;

constunsignedchar* dataBuffer = (constunsignedchar*)[hexData bytes];

if(!dataBuffer){

returnnil;

    }

NSUInteger dataLength = [hexData length];

NSMutableString* hexString = [NSMutableStringstringWithCapacity:(dataLength * 2)];

for(int i = 0; i < dataLength; i++){

        [hexString appendString:[NSStringstringWithFormat:@"%02lx", (unsignedlong)dataBuffer[i]]];

    }

    result = [NSStringstringWithString:hexString];

return result;

}

+(NSData*)coverFromStringToHexData:(NSString*)string

{

return  [string dataUsingEncoding: NSUTF8StringEncoding];

}

+(void)coverFromBytesArrToData

{

Byte byte[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};

NSData *adata = [[NSDataalloc] initWithBytes:byte length:24];

NSLog(@"位元組陣列轉換的data 資料為: %@",adata);

}

+(void)coverFromBytesArrToHexStr

{

NSString *aString = @"1234abcd";

NSData *aData = [aString dataUsingEncoding: NSUTF8StringEncoding];

//    NSData* aData = [[NSData alloc] init];

Byte *bytes = (Byte *)[aData bytes];

/**           

: bytes  即為位元組陣列類似於 Byte bts[] = {1,2,3,4,5};

     **/

NSLog(@"%s",bytes);

NSString *hexStr=@"";

for(int i=0;i<[aData length];i++)

    {

NSString *newHexStr = [NSStringstringWithFormat:@"%x",bytes[i]&0xff];///16進位制數

if([newHexStr length]==1)

            hexStr = [NSStringstringWithFormat:@"%@0%@",hexStr,newHexStr];

else

            hexStr = [NSStringstringWithFormat:@"%@%@",hexStr,newHexStr];

    }

NSLog(@"bytes 16進位制數為:%@",hexStr);

NSLog(@"data 16進位制數為:%@",aData);

}

+(NSString*)coverFromDataToHexStr:(NSData *)data

{

constunsignedchar* dataBuffer = (constunsignedchar*)[data bytes];

NSUInteger dataLength = [data length];

NSMutableString* hexString = [NSMutableStringstringWithCapacity:(dataLength * 2)];

for(int i = 0; i < dataLength; i++){

        [hexString appendString:[NSStringstringWithFormat:@"%02lx", (unsignedlong)dataBuffer[i]]];

    }

return [NSStringstringWithString:hexString];

}

+(UInt64)coverFromHexStrToInt:(NSString *)hexStr

{

UInt64 mac1 =  strtoul([hexStr UTF8String], 0, 16);

return mac1;

}

+(NSString *)coverFromIntToHex:(NSInteger)tmpid

{

NSString *nLetterValue;

NSString *str =@"";

long longint ttmpig;

for (int i = 0; i<9; i++) {

        ttmpig=tmpid%16;

        tmpid=tmpid/16;

switch (ttmpig)

        {

case10:

                nLetterValue =@"A";break;

case11:

                nLetterValue =@"B";break;

case12:

                nLetterValue =@"C";break;

case13:

                nLetterValue =@"D";break;

case14:

                nLetterValue =@"E";break;

case15:

                nLetterValue =@"F";break;

default:nLetterValue=[[NSStringalloc]initWithFormat:@"%lli",ttmpig];

        }

        str = [nLetterValue stringByAppendingString:str];

if (tmpid == 0) {

break;

        }

    }

if(str.length == 1){

return [NSStringstringWithFormat:@"0%@",str];

    }else{

return str;

    }

}

+(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 = [NSDatadataWithBytes:bytes length:4];

return data;

}

+(NSData*)coverToByteWithData:(int)timeInterval

{

char *p_time = (char *)&timeInterval;

char str_time[4] = {0};

for(int i= 0 ;i < 4 ;i++)

    {

        str_time[i] = *p_time;

        p_time ++;

    }

NSData* bodyData = [NSDatadataWithBytes:str_time length:4];

return bodyData;

}

+(int) setDa:(NSData*)intData

{

int value = CFSwapInt32BigToHost(*(int*)([intData bytes]));//655650

return value;

}