给定一个obj-c无符号字节数组,如何在Java中获取等效的字节值?

时间:2022-11-25 11:30:23

I have a byte array in an iOS application,

我在iOS应用程序中有一个字节数组,

const uint8 unsignedByteArray[] = {189U, 139U, 64U, 0U};

I need to send these same exact values from an Android device running Java.

我需要从运行Java的Android设备发送这些相同的确切值。

Is there a way to reliably convert the unsigned values into something Java can use and send that is equivalent to the byte values on iOS?

有没有办法可靠地将无符号值转换为Java可以使用和发送的东西,这相当于iOS上的字节值?

1 个解决方案

#1


1  

In Objective-c, create a hex string from the data...

在Objective-c中,从数据中创建一个十六进制字符串......

const uint8_t bytes[] = {189U, 139U, 64U, 0U};
NSMutableString *result  = [NSMutableString string];

for (int i = 0; i < 4; ++i) {
    [result appendFormat:@"%02x", (uint8_t)bytes[i]];
}
NSLog(@"%@",result);

This will result in....

这将导致......

bd8b4000

Then apply an idea like this in java (copied the code here verbatim)...

然后在java中应用这样的想法(在这里逐字复制代码)...

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

#1


1  

In Objective-c, create a hex string from the data...

在Objective-c中,从数据中创建一个十六进制字符串......

const uint8_t bytes[] = {189U, 139U, 64U, 0U};
NSMutableString *result  = [NSMutableString string];

for (int i = 0; i < 4; ++i) {
    [result appendFormat:@"%02x", (uint8_t)bytes[i]];
}
NSLog(@"%@",result);

This will result in....

这将导致......

bd8b4000

Then apply an idea like this in java (copied the code here verbatim)...

然后在java中应用这样的想法(在这里逐字复制代码)...

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