how hexadecimal string to Bytes and Bytes to hexadecimal string? I have oc code but I can not to write in swift can u help me ? thanks so much
+ (NSData *)convertHexToDataBytes:(NSString *)hexStr {
NSMutableData *dataBytes = [NSMutableData data];
int idx;
for (idx = 0; idx + 2 <= hexStr.length; idx += 2) {
NSRange range = NSMakeRange(idx, 2);
NSString *singleHexStr = [hexStr substringWithRange:range];
NSScanner *scanner = [NSScanner scannerWithString:singleHexStr];
unsigned int intValue;
[scanner scanHexInt:&intValue];
[dataBytes appendBytes:&intValue length:1];
}
return dataBytes;
}
+ (NSString *)convertDataBytesToHex:(NSData *)dataBytes {
if (!dataBytes || [dataBytes length] == 0) {
return @"";
}
NSMutableString *hexStr = [[NSMutableString alloc] initWithCapacity:[dataBytes length]];
[dataBytes enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
unsigned char *dataBytes = (unsigned char *)bytes;
for (NSInteger i = 0; i < byteRange.length; i ++) {
NSString *singleHexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
if ([singleHexStr length] == 2) {
[hexStr appendString:singleHexStr];
} else {
[hexStr appendFormat:@"0%@", singleHexStr];
}
}
}];
return hexStr;
}
I write in swift like this
class func convertHex(toDataBytes hexStr: String?) -> Data? {
var dataBytes = Data()
var idx: Int
idx = 0
while idx + 2 <= (hexStr?.count ?? 0) {
let range = NSRange(location: idx, length: 2)
let singleHexStr = (hexStr as NSString?)?.substring(with: range)
let scanner = Scanner(string: singleHexStr ?? "")
var intValue: UInt
scanner.scanHexInt32(&UInt32(intValue))
dataBytes.append(&intValue, count: 1)
idx += 2
}
return dataBytes
}
its error says:Cannot pass immutable value as inout argument: function call returns immutable value how to fix it?