java接收nsdata 二进制,16进制字符串与NSData,数字,二进制字符串之间的转化

16进制字符串转化为数字:

+ (NSInteger)numberWithHexString:(NSString*)hexString{

const char *hexChar = [hexString cStringUsingEncoding:NSUTF8StringEncoding];

int hexNumber;

sscanf(hexChar,"%x", &hexNumber);

return  (NSInteger)hexNumber;

}

十六进制字符串转换为二进制字符串:

+ (NSString*)getBinaryByHex:(NSString*)hex {

NSMutableDictionary *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"];

NSString*binary =@"";

for(inti=0; i

NSString *key = [hex substringWithRange:NSMakeRange(i, 1)];

NSString*value = [hexDicobjectForKey:key.uppercaseString];

if(value) {

binary = [binarystringByAppendingString:value];

}

}

return binary;

}

16进制字符串转化为NSData:

-(NSData*) hexToBytes:(NSString*)str {

NSMutableData* data = [NSMutableData data];

intidx;

for(idx =0; idx+2<= str.length; idx+=2) {

NSRangerange =NSMakeRange(idx,2);

NSString* hexStr = [strsubstringWithRange:range];

NSScanner* scanner = [NSScannerscannerWithString:hexStr];

unsignedintintValue;

[scannerscanHexInt:&intValue];

[dataappendBytes:&intValuelength:1];

}

returndata;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值