如何将文本字符串转换为十六进制字符串?

Ame*_*has 5 string hex ios

假设我有一个文本字符串:"向我的小朋友问好"

函数应返回十六进制值:

5361792048656c6c6f20746f204d79204c6974746c6520467269656e64

sma*_*8dd 7

Swift 4,Swift 3

let hex: String = "ABC".unicodeScalars.filter { $0.isASCII } .map { String(format: "%X", $0.value) } .joined() print(hex) // correctly yields 414243


Ron*_*ara 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);
Run Code Online (Sandbox Code Playgroud)

上面的代码给出了您所给出的确切字符串:

5361792048656c6c6f20746f204d79204c6974746c6520467269656e64

希望它会有所帮助:)