16進数と文字列の相互変換
3448 ワード
========================================================================文字列回転16進 16進数回転文字列
ここで、16進数文字列をNSDataに変換するコードは次のとおりです.
NSDataを16進数の文字列に変換するには、次のようにします.
===================================文字列回転16進
+ (NSString *)hexStringFromString:(NSString *)string {
NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
Byte *bytes = (Byte *)[myD bytes];
// Byte 16 。
NSString *hexStr=@"";
for(int i=0;i
+ (NSString *)stringFromHexString:(NSString *)hexString {
char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
bzero(myBuffer, [hexString length] / 2 + 1);
for (int i = 0; i < [hexString length] - 1; i += 2) {
unsigned int anInt;
NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
[scanner scanHexInt:&anInt];
myBuffer[i / 2] = (char)anInt;
}
NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
NSLog(@"------ =======%@",unicodeString);
return unicodeString;
}
ここで、16進数文字列をNSDataに変換するコードは次のとおりです.
- (NSData *)convertHexStrToData:(NSString *)str {
if (!str || [str length] == 0) {
return nil;
}
NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
NSRange range;
if ([str length] % 2 == 0) {
range = NSMakeRange(0, 2);
} else {
range = NSMakeRange(0, 1);
}
for (NSInteger i = range.location; i < [str length]; i += 2) {
unsigned int anInt;
NSString *hexCharStr = [str substringWithRange:range];
NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
[scanner scanHexInt:&anInt];
NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
[hexData appendData:entity];
range.location += range.length;
range.length = 2;
}
LEDEBUG(@"hexdata: %@", hexData);
return hexData;
}
NSDataを16進数の文字列に変換するには、次のようにします.
- (NSString *)convertDataToHexStr:(NSData *)data {
if (!data || [data length] == 0) {
return @"";
}
NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
[data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
unsigned char *dataBytes = (unsigned char*)bytes;
for (NSInteger i = 0; i < byteRange.length; i++) {
NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
if ([hexStr length] == 2) {
[string appendString:hexStr];
} else {
[string appendFormat:@"0%@", hexStr];
}
}
}];
return string;
}
===================================
class func hexStringFromString(str:String) -> String {
let data:Data = str.data(using:.utf8)!
var hexStr = ""
for i in 0 ..< data.count {
let mHexStr:NSString = NSString.init(format: "%x", data[i]&0xff)
if mHexStr.length == 1 {
hexStr = String(format: "%@0%@", hexStr,mHexStr)
} else {
hexStr = String(format: "%@%@", hexStr,mHexStr)
}
}
return hexStr
}