【问题标题】:Convert 7 lines of Objective C code to Java [closed]将 7 行 Objective C 代码转换为 Java [关闭]
【发布时间】:2013-11-12 20:22:27
【问题描述】:

我已经尝试了几个小时来用 Java 实现这段代码。该代码使用指针,我不知道如何在 Java 中做同样的事情。我试过移位但没有成功。有任何想法吗?

const char bytes[] = {0xa0,0xc7,0xa2,0xbc,0xd4};
NSData *data = [[NSData alloc] initWithBytes:bytes length:5];
uint8_t *byte = (uint8_t*)[data bytes];
uint8_t command = *byte;
byte++;
NSUInteger password = *(uint32_t*)byte;
NSLog(@"password:%u", (uint32_t)password );  // answer: 3569132231

【问题讨论】:

    标签: java android ios objective-c


    【解决方案1】:

    这是工作示例:

    import java.nio.ByteBuffer;
    import java.nio.ByteOrder;
    
    class Test {
        public static void main(String[] args) {
    
            byte[] bytes = {(byte)0xa0,(byte)0xc7,(byte)0xa2,(byte)0xbc,(byte)0xd4};
            ByteBuffer wrapped = ByteBuffer.wrap(bytes);
            wrapped.order(ByteOrder.LITTLE_ENDIAN);
            System.out.println(wrapped.getInt(1) & 0x00000000ffffffffL);
        }
    }
    

    【讨论】:

      【解决方案2】:

      命令是数组的第一个字节,最后四个字节是密码。

      这是一段与您提供的代码相同的代码:

      public static void main(String... args) throws IOException {
          byte b[] = new byte[]{
                  (byte) 0xa0, (byte) 0xc7, (byte) 0xa2, (byte) 0xbc, (byte) 0xd4
          };
      
          byte command = b[0];
          long password = 0;
          for (int i = 1; i < b.length; i++) {
              password += ((long) b[i] & 0xffL) << (8 * (i - 1));
          }
          System.out.println(password);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-28
        • 1970-01-01
        相关资源
        最近更新 更多