如何在Objective-C中将NSString转换为HEX String? [英] How to convert NSString to HEX String in Objective-C?
本文介绍了如何在Objective-C中将NSString转换为HEX String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个NSString,其字符串类似于hello。
现在我想将字符串转换为另一个显示十六进制字符串的NSString对象。怎么做?
解决方案
嗯 - 除了可以在其他地方找到的显而易见的东西之外 - 怎么样:
NSString * str = @Hello World;
NSString * hexStr = [NSString stringWithFormat:@%@,
[NSData dataWithBytes:[str cStringUsingEncoding:NSUTF8StringEncoding]
length:strlen([str cStringUsingEncoding:NSUTF8StringEncoding] )]];
for(NSString * toRemove in [NSArray arrayWithObjects:@<,@>,@,nil])
hexStr = [hexStr stringByReplacingOccurrencesOfString:toRemove withString: @ ];
NSLog(@%@,hexStr);
这应该给出类似
$ b <$ p的输出$ p>
48656c6c6f20576f726c64
优化这是留给读者的练习: ):)
I have a NSString with string like "hello".
Now I want to convert the string into another NSString object which shows a hex string. How to do that ?
解决方案
Hmm - apart from the obvious which can be found elsewhere - how about something like:
NSString * str = @"Hello World";
NSString * hexStr = [NSString stringWithFormat:@"%@",
[NSData dataWithBytes:[str cStringUsingEncoding:NSUTF8StringEncoding]
length:strlen([str cStringUsingEncoding:NSUTF8StringEncoding])]];
for(NSString * toRemove in [NSArray arrayWithObjects:@"<", @">", @" ", nil])
hexStr = [hexStr stringByReplacingOccurrencesOfString:toRemove withString:@""];
NSLog(@"%@", hexStr);
which should give an output like
48656c6c6f20576f726c64
Optimising this is left as an exercise to the reader :) :)
这篇关于如何在Objective-C中将NSString转换为HEX String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文