我是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);
现在我无法在Swift中转换此函数。目前我正在使用Swift3。
请有人可以帮我吗?
答案 0 :(得分:7)
这产生与ObjC版本相同的输出
let str = "Say Hello to My Little Friend"
let data = Data(str.utf8)
let hexString = data.map{ String(format:"%02x", $0) }.joined()
答案 1 :(得分:0)
将您的字符串转换为NSData,如下所示。
let myString = "ABCDEF"
let data = myString.dataUsingEncoding(NSUTF8StringEncoding)
然后使用以下方法将NSData转换为十六进制字符串 -
func hexFromData(data:NSData) -> String {
let p = UnsafePointer<UInt8>(data.bytes)
let len = data.length
var str: String = String()
for i in 0...len-1 {
str += String(format: "%02.2X", p[i])
}
return str
}
希望这会有所帮助。
答案 2 :(得分:0)
请试试这个,
let string = "Say Hello to My Little Friend"
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
print(data)
,其输出为:
Optional(<53617920 48656c6c 6f20746f 204d7920 4c697474 6c652046 7269656e 64>)
答案 3 :(得分:0)
@GET("/friends")
Call<ResponseBody> friends(@Query(value="group", encoded=true) String group);
extension String {
func toHexEncodedString(uppercase: Bool = true, prefix: String = "", separator: String = "") -> String {
return unicodeScalars.map { prefix + .init($0.value, radix: 16, uppercase: uppercase) } .joined(separator: separator)
}
}
答案 4 :(得分:-1)
Swift 3
let string = "Hello World!"
let data = string.data(using: String.Encoding.utf8)
let hexString = data?.hex
extension Data {
var hex: String {
var string = ""
#if swift(>=3.1)
enumerateBytes { pointer, index, _ in
for i in index..<pointer.count {
string += String(format: "%02x", pointer[i])
}
}
#else
enumerateBytes { pointer, count, _ in
for i in 0..<count {
string += String(format: "%02x", pointer[i])
}
}
#endif
return string
}
}