请帮帮我。 我有这个代码来获取从正常可读字符串发送到服务器所需的字符串
- (NSString *)hexForWindowsCP1251 //"Привет"
{
size_t theLength = strlen([self cStringUsingEncoding:NSWindowsCP1251StringEncoding]);
const char *selfChar = [self cStringUsingEncoding:NSWindowsCP1251StringEncoding];
NSData *stringData = [NSData dataWithBytes:selfChar length:theLength];
NSString * hexStr = [NSString stringWithFormat:@"%@", stringData];
for(NSString * toRemove in [NSArray arrayWithObjects:@"<", @">", @" ", nil])
{
hexStr = [hexStr stringByReplacingOccurrencesOfString:toRemove withString:@""];
}
return hexStr; //cff0e8e2e5f2
}
英语和俄语文本都可以(我的字符串是“12e314f4”)
我不知道如何从这样的字符串中获取可读文本。
例如字符串“Привет”(俄语版本)变为“cff0e8e2e5f2”
我需要反之亦然得到字符串“Hello”(如果是用英语编码的)和“Привет”(如果是用俄语编码的话)......
答案 0 :(得分:0)
我终于得到了转换为十六进制字符串并返回的工作流程。
这三种方法在NSString类别中实现:
//To get hexEncoded string to pass to server:
- (NSString *)hexForWindowsCP1251
{
size_t theLength = strlen([self cStringUsingEncoding:NSWindowsCP1251StringEncoding]);
const char *selfChar = [self cStringUsingEncoding:NSWindowsCP1251StringEncoding];
// \xef\xf0\xe8
NSData *stringData = [NSData dataWithBytes:selfChar length:theLength];
NSString * hexStr = [NSString stringWithFormat:@"%@", stringData];
for(NSString * toRemove in [NSArray arrayWithObjects:@"<", @">", @" ", nil])
{
hexStr = [hexStr stringByReplacingOccurrencesOfString:toRemove withString:@""];
}
return hexStr;
}
//To make the string readable
- (NSString *)hexToStringNSWIndows1251
{
NSData *bytes = [self dataFromHexString];
NSString *toReturn = [[NSString alloc] initWithData:bytes encoding:NSWindowsCP1251StringEncoding];
return toReturn;
}
- (NSData *)dataFromHexString
{
const char *chars = [self UTF8String];
int i = 0, len = self.length;
NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
char byteChars[3] = {'\0','\0','\0'};
unsigned long wholeByte;
while (i < len) {
byteChars[0] = chars[i++];
byteChars[1] = chars[i++];
wholeByte = strtoul(byteChars, NULL, 16);
[data appendBytes:&wholeByte length:1];
}
return data;
}