字符编码和文字的互转
2016-11-22 本文已影响68人
囧书
写个工具,实现字符编码和文字的互转。比如GBK字符码转中文。
给NSString扩展分类
@interface NSString (ConvertEncoding)
#pragma mark - GBK
/// 把十六进制GBK编码转成文字
- (instancetype)convertToGBKCharacters;
/// 把文字转成十六进制GBK编码
- (instancetype)convertToGBKCode;
#pragma mark - UTF8
/// 把十六进制UTF8编码转成文字
- (instancetype)convertToUTF8Characters;
/// 把文字转成十六进制UTF8编码
- (instancetype)convertToUTF8Code;
#pragma mark - Public
/// 把十六进制编码转成文字
- (instancetype)convertToCharactersWithEncoding:(NSStringEncoding)encoding;
/// 把文字转成十六进制编码
- (instancetype)convertToCodeWithEncoding:(NSStringEncoding)encoding;
/// 把十六进制字符串转成NSData
- (NSData *)convertToHexData;
/// 把NSData转成十六进制字符串
+ (instancetype)hexStringFromData:(NSData *)data;
@end
简单使用
NSString *gbk = @"C4E3BAC3";
NSString *characters = [gbk convertToGBKCharacters];
NSLog(@"把十六进制GBK编码转成文字:%@ --> %@", gbk, characters);
characters = @"你好";
gbk = [characters convertToGBKCode];
NSLog(@"把文字转成十六进制GBK编码:%@ --> %@", characters, gbk);
NSString *utf8 = @"E6849FE8B0A2";
characters = [utf8 convertToUTF8Characters];
NSLog(@"把十六进制UTF8编码转成文字:%@ --> %@", utf8, characters);
characters = @"感谢";
utf8 = [characters convertToUTF8Code];
NSLog(@"把文字转成十六进制UTF8编码:%@ --> %@", characters, utf8);
控制台输出