相关疑难解决方法(0)

在Swift中将十六进制字符串转换为NSData

我得到了在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)

objective-c ios swift

32
推荐指数
5
解决办法
3万
查看次数

如何在Swift 3中将HexString转换为ByteArray

我正在尝试将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:"蒸汽"

byte swift swift3

3
推荐指数
1
解决办法
5837
查看次数

Swift中的十六进制/二进制字符串转换

Python有两个非常有用的库方法(binascii.a2b_hex(keyStr)和binascii.hexlify(keyBytes)),我一直在Swift中苦苦挣扎.Swift中有什么随处可用的吗?如果没有,将如何实现它?给定所有边界和其他检查(如偶数长度键).

python hex bin swift

2
推荐指数
1
解决办法
2449
查看次数

标签 统计

swift ×3

bin ×1

byte ×1

hex ×1

ios ×1

objective-c ×1

python ×1

swift3 ×1