开发者

Objective-C conversion of hex characters and Java convert hex characters are not the same?

开发者 https://www.devze.com 2023-04-06 02:21 出处:网络
Objective-C, convert NSData hexadecimal characters and Java byte array into a hexadecimal character is not the same, what this approach into the same?

Objective-C, convert NSData hexadecimal characters and Java byte array into a hexadecimal character is not the same, what this approach into the same?

Java code:

public static String convertByteToHexString(byte[] bytes){
          StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            builder.append(String.format("%02X", b));
        }
       return builder.toString().toUpperCase();
 } 



public static byte[] convertHexString(String ss) {
            int length = ss.length() / 2;
    byte digest[] = new byte[length];
    for (int i = 0; i < length; i++) {
        String byteString = ss.substring(2 * i, 2 * i + 2);
        int byteValue = Integer.parseInt(byteString, 16);
        digest[i] = (byte) byteValue;
    }
    return digest;
}

Objective-C code:

+(NSString*)hexStringForData:(NSData*)data{
if (data == nil) {
    return nil;
}

NSMutableString* hexString = [NSMutableString string];

const unsigned char *p = [data bytes];

for (int i=0; i < [data length]; i++) {
    [hexString appendFormat:@"%02x", *p++];
}
return hexString;

}

+ (NSData*)dataForHexString:(NSString*)hexString{
if (hexString == nil) {
    return nil;
}

const char* ch = [[hexString lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];
NSMutableData* data = [NSMutableData data];
while (*ch) {
    char byte = 0;
    if ('0' <= *ch && *ch <= '9') {
        byte = *ch - '0';
    } else if ('a' <= *ch && *ch <= 'f') {
        byte = *ch - 'a' + 10;
    }
    ch++;
    byte = byte << 4;
    if (*ch) {
        if ('0' <= *ch && *ch <= '9') {
            byte += *ch - '0';
        } else if ('a' <= *ch && *ch <= 'f') {
            byte += *ch - 'a' + 10;
        }
        ch++;
    }
    [data appendBytes:&byte length:1];
}
return data;

}

c# code:

public static string convertByteArrayToHex(byte[] byte){

        StringBuilder builder = new StringBuilder();
        foreach (byte num in byte)
        {
            builder.AppendFormat("{0:X2}", num);
        }
        stream.Close();
        return builder.ToString();

}

public static byte[] convertHexToByteArray(string str){
  int length = str.Length/2;
  byte[] buf开发者_运维技巧fer = new byte[length];
        for (int i = 0; i < length; i++)
        {
            int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
            buffer[i] = (byte)num2;
        }
 return buffer;

}

========================= Java c # the same, only the Objective-C。。。

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号