数据转换工具.h文件
#define ZZDataShare [ZZDataTool sharedTool]
@interface ZZDataTool : NSObject
+ (instancetype)sharedTool;
#pragma mark - int 与 NSData 转换
//int转data
-(NSData *)intToData:(int)i;
//data转int
-(int)dataToInt:(NSData *)data;
#pragma mark - 字符串与NSData转换
//16进制数字字符串转,转NSData
- (NSData *)hexToBytes:(NSString *)str;
//普通字符串,转NSData
- (NSData *)stringToBytes:(NSString *)str;
//NSdata 转16进制普通字符串
- (NSString *)hexadecimalStringWithData:(NSData *)data;
- (NSString *)hexRepresentationWithSpaces_AS:(BOOL)spaces withData:(NSData *)data;
- (NSString *)hexRepresentationWithSymbol:(NSString *)symbol withData:(NSData *)data;
#pragma mark - 字符串与字符串之间转换
//十六进制数字字符串转换为10进制数字字符串的。
- (NSString *)hexNumberStringToNumberString:(NSString *)hexNumberString;
//十进制数字字符串转换为16进制数字字符串的。
- (NSString *)numberStringToHexNumberString:(NSString *)numberString;
// 十六进制转换为普通字符串的。
- (NSString *)stringFromHexString:(NSString *)hexString;
//普通字符串转换为十六进制的。
- (NSString *)hexStringFromString:(NSString *)string;
#pragma mark - Dictionary 转 Json String
-(NSString *)dictionaryToJsonStr:(id)dic;
@end
数据转换工具.m文件
#import "ZZDataTool.h"
@implementation ZZDataTool
+ (instancetype)sharedTool {
static id instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
#pragma mark - int 与 NSData 转换
//int转data
-(NSData *)intToData:(int)i{
NSData *data = [NSData dataWithBytes: &i length: sizeof(i)];
return data;
}
//data转int
-(int)dataToInt:(NSData *)data{
int i;
[data getBytes:&i length:sizeof(i)];
return i;
}
#pragma mark - 字符串与NSData转换
//16进制字符转(不带0x),转NSData
-(NSData *)hexToBytes:(NSString *)str{
NSMutableData * data = [NSMutableData data];
for (int i = 0; i+2 <= str.length; i+=2) {
NSString * subString = [str substringWithRange:NSMakeRange(i, 2)];
NSScanner * scanner = [NSScanner scannerWithString:subString];
uint number;
[scanner scanHexInt:&number];
[data appendBytes:&number length:1];
}
return data.copy;
}
//普通字符串,转NSData
- (NSData *)stringToBytes:(NSString *)str{
return [str dataUsingEncoding:NSASCIIStringEncoding];
}
//NSdata 转16进制字符串
- (NSString *)hexadecimalStringWithData:(NSData *)data
{
/* Returns hexadecimal string of NSData. Empty string if data is empty. */
const unsigned char *dataBuffer = (const unsigned char *)[data bytes];
if (!dataBuffer)
{
return [NSString string];
}
NSUInteger dataLength = [data length];
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i)
{
[hexString appendFormat:@"%02x", (unsigned int)dataBuffer[i]];
}
return [NSString stringWithString:hexString];
}