Objective-C, преобразование шестнадцатеричных символов NSData и байтового массива Java в шестнадцатеричный символ не то же самое, что этот подход в то же самое?
Java-код:
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:
+(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 # код:
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[] buffer = 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 # то же самое, только Objective-C 。。。