假设我有一个文字字符串: “向我的小朋友问好”
函数应将十六进制值返回为:
5361792048656c6c6f20746f204d79204c6974746c6520467269656e64
答案 0 :(得分:7)
Swift 4,Swift 3
Tuple
答案 1 :(得分:3)
你可以这样做,
NSString *str = @"Say Hello to My Little Friend";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data %@",data);
视频输出:data <53617920 48656c6c 6f20746f 204d7920 4c697474 6c652046 7269656e 64>
<强>夫特:强>
let string = "Say Hello to My Little Friend"
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
斯威夫特3:
let string = "Say Hello to My Little Friend"
let data = string.data(using: String.Encoding.utf8)
答案 2 :(得分:2)
无法用swift编写,但在Objective-C下面的代码可能就是你要找的东西:
NSString * str = @"Say Hello to My Little Friend";
NSString * hexString = [NSString stringWithFormat:@"%@",
[NSData dataWithBytes:[str cStringUsingEncoding:NSUTF8StringEncoding]
length:strlen([str cStringUsingEncoding:NSUTF8StringEncoding])]];
for(NSString * toRemove in [NSArray arrayWithObjects:@"<", @">", @" ", nil])
hexString = [hexString stringByReplacingOccurrencesOfString:toRemove withString:@""];
NSLog(@"hexStr:%@", hexString);
上面的代码给出了你给出的精确字符串:
5361792048656c6c6f20746f204d79204c6974746c6520467269656e64
希望它会有所帮助:)