简体   繁体   中英

How to write HexStringToData in java the same as Swift Example?

I writing and app in Java using Android studio and I would appreciate a little help, as I have this example below in Swift 2.3 :

private func hexStringToData(hexString: String) -> NSData {

    print("String: \(hexString)")

    let chars = Array(hexString.characters)

    let numbers = 0.stride(to: chars.count, by: 2).map {
        UInt8(String(chars[$0 ..< $0+2]), radix: 16) ?? 0
    }
    return NSData(bytes: numbers, length: numbers.count)

}

I would like to know if it is possible to have the equivalent in Java, I've tried the code below, but this seems to fail on : Invalid array range:6 to 6 an example of the code is below:

private static byte[]hexStringToData (String hexString) {

    Log.e("[hexStringToData]String", ":" + hexString);

    int len = hexString.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                + Character.digit(hexString.charAt(i+1), 16));
    }
    return data; 
}

Can someone please tell me where it is I'm going wrong, thanks in advance....

This is the string : A4728E4491AA598E0473C2EB860C8872B8F53630329C97B8D7FF1A0F9BC5‌​487E971CAD562E7C4C7A‌​2847CFB4681F0E563B66‌​7A6E6E09FBF60378A302‌​44E0981A46CB17BA3F22‌​8A4DD89360B3C4CB156D‌​794E9ADE22F55F55A6A7‌​E76A726588B1C615774E‌​713F6D1E59D7B1D82E2B‌​913330AB92C1DB595054‌​0FFC2C9B6ED0889000A9‌​51778F3A82C1CCB16651‌​DFFAA6C6A40EEE9FFB24‌​217F85C57A190757BF57‌​4ADC9D9A7E38DBC3B7B3‌​61AFC0D3C36A76916DEF‌​493633708E9D9BFB639F‌​8D2499C2A71D6E8A52F6‌​34050BD3FF1260502E8A‌​2834B1FB56BED29CAB1B‌​3993EA669313ECD63FC9‌​911F1BFF1EA4AAC5410D‌​E9E2D80AE5B05F701EDD‌​4F06B5CD532

原来我犯了一个男生错误:hexStringToData(file),“ file-0001.rsa”,我试图转换文件名本身而不是实际的文件本身,所以我的长度是13,因为文件名和长度应为文件的512。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM