我得到了在Objective-C中将String转换为HEX-String的代码.
- (NSString *) CreateDataWithHexString:(NSString*)inputString
{
NSUInteger inLength = [inputString length];
unichar *inCharacters = alloca(sizeof(unichar) * inLength);
[inputString getCharacters:inCharacters range:NSMakeRange(0, inLength)];
UInt8 *outBytes = malloc(sizeof(UInt8) * ((inLength / 2) + 1));
NSInteger i, o = 0;
UInt8 outByte = 0;
for (i = 0; i < inLength; i++) {
UInt8 c = inCharacters[i];
SInt8 value = -1;
if (c >= '0' && c <= '9') value = (c - '0');
else if (c >= 'A' && c <= 'F') value …Run Code Online (Sandbox Code Playgroud) 我正在尝试将hexString转换为字节数组([UInt8])我搜索到了所有地方但找不到解决方案.下面是我的快速2代码
func stringToBytes(_ string: String) -> [UInt8]? {
let chars = Array(string)
let length = chars.count
if length & 1 != 0 {
return nil
}
var bytes = [UInt8]()
bytes.reserveCapacity(length/2)
for var i = 0; i < length; i += 2 {
if let a = find(hexChars, chars[i]),
let b = find(hexChars, chars[i+1]) {
bytes.append(UInt8(a << 4) + UInt8(b))
} else {
return nil
}
}
return bytes
}
Run Code Online (Sandbox Code Playgroud)
示例Hex
十六进制:"7661706f72"
expectedOutput:"蒸汽"
Python有两个非常有用的库方法(binascii.a2b_hex(keyStr)和binascii.hexlify(keyBytes)),我一直在Swift中苦苦挣扎.Swift中有什么随处可用的吗?如果没有,将如何实现它?给定所有边界和其他检查(如偶数长度键).