如果我将NSData转换为字符串,就像这样
NSString *someString = [NSString stringWithFormat:@"%@", hashedData];
如何将someString转换回hashedData?
例如,在以下代码中
NSString *string = @"This is a string";
NSData *data1 = [string dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data: %@",data1);
NSString *dataString = [NSString stringWithFormat:@"%@",data1];
NSData* data2 = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data2: %@",data2);
我得到以下输出
data1: <54686973 20697320 61207374 72696e67>
data2: <3c353436 38363937 33203230 36393733 32302036 31323037 33373420 37323639 36653637 3e>
我想要的是data2应该与data1相同。我的意思是将dataString转换回原始的hashedData。
答案 0 :(得分:1)
替换你的代码:
NSString *string = @"This is a string";
NSData *data1 = [string dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data: %@",data1);
NSString *dataString = [NSString stringWithUTF8String:[data1 bytes]];
NSData* data2 = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data2: %@",data2);
<强>输出:强>
Demoapp [1024:22267]数据:&lt; 54686973 20697320 61207374 72696e67&gt; 2015-09-04 12:52:10.104 Demoapp [1024:22267] data2:&lt; 54686973 20697320 61207374 72696e67 02&gt;
答案 1 :(得分:1)
你无法直接将NSData
分配给NSString
,你必须像这样将NSData转换为NSString
NSString *dataString = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
检查更新的代码
NSString *string = @"This is a string";
NSData *data1 = [string dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data: %@",data1);
NSString *dataString = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
NSData* data2 = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data2: %@",data2);
现在NSData
都是相同的
答案 2 :(得分:0)
将数据转换为字符串: -
NSData *data ;
NSLog(@"data is :%@",data);
NSString *strr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Responce is : %@",strr);
现在将字符串转换为数据: -
NSData *dataa = [strr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data is :%@",dataa);
2015-09-04 12:43:54.502 TokenPic[2003:60b] data is :<7b227375 63636573 73223a22 31222c22 706f7374 73223a22 4576656e 74204372 65617465 64205375 63636573 7366756c 6c792e22 7d>
2015-09-04 12:44:01.165 TokenPic[2003:60b] Responce is : {"success":"1","posts":"Event Created Successfully."}
2015-09-04 12:44:02.801 TokenPic[2003:60b] data is :<7b227375 63636573 73223a22 31222c22 706f7374 73223a22 4576656e 74204372 65617465 64205375 63636573 7366756c 6c792e22 7d>
答案 3 :(得分:0)
在Swift 1.2中将NSData
转换为NSString
:
let stringFromData = NSString(data: data, encoding: NSUTF8StringEncoding)
在Swift 1.2中将NSString
转换为NSData
:
let dataFromString = myString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)