【问题标题】:Little and Big Endian in Java (android)Java 中的小端和大端 (android)
【发布时间】:2016-05-19 17:40:16
【问题描述】:

我正在使用 Android Studio 构建一个应用,在我的项目中,我需要进行很多转换,例如将 short/int 转换为字节数组。我还希望我的应用程序从用 C 编码的机器人接收数据,并且机器人发送一个包含很多 uint16-32、int16-32 的结构...... 我发现很多帖子和代码可以帮助我在字节数组中转换我的属性,但我总是看到人们在谈论 Little Endian 和 Big Endian,我无法理解其中的区别。如果有人可以向我解释...... 注意:机器人通过带有 TCP 协议的 Wifi 套接字发送数据

【问题讨论】:

标签: java android tcp type-conversion endianness


【解决方案1】:

Little Endian 和 Big Endian 只是指数据结构的字节的呈现顺序。

想象一下,您有一个 16 位整数,由十六进制值 0xabcd 表示。因为 8 位 = 1 字节,所以我们的整数由两个字节组成,ab 和 cd。在 Big Endian 系统中,最高有效字节放在较低的内存地址中,而在 Little Endian 系统中,我们将它们放在较高的内存地址中。

为了直观地展示这一点,假设我们将整数放在内存地址 0 处。

在 Big Endian 系统中,我们的内存应该是这样的:

Memory address  -> |  0 |  1 |
Value           -> | ab | cd |

在 Little Endian 系统中,它看起来像这样:

Memory address  -> |  0 |  1 |
Value           -> | cd | ab |

传统上,网络字节顺序是Big Endian。

【讨论】:

  • Android(原生)是 Little-Endian。
【解决方案2】:

在将整数转换为字节流时,通常将整数分成字节,逐个发送。如果发送的第一个字节包含最低有效位,则它是小端。如果发送的第一个字节包含最高有效位,则为大端。在 little endian 中,1 将由字节 1 后跟一个包含 0 的字节表示。(由于字节可以用两个十六进制数字表示,因此它们通常以这种方式表示。)因此,短整数 1 被转换为字节 01 00短整数 256 变成小端序中的字节 00 01。在大端中,1的字节流是00 01,256变成01 00。

https://en.wikipedia.org/wiki/Endianness

【讨论】:

    【解决方案3】:
    String path=”root/subdir/filename.extension”;
    
    File f=new File(path);
    
    RandomAccessFile raf=new RandomAccessFile(f,”r”);
    
     ByteBuffer bb;
    
       char c;
    
     int i;
    
    
    
        ch=raf.readChar();
    
          bb=ByteBuffer.allocate(4); //4 byte buffer
    
     bb.order(ByteOrder.BIG_ENDIAN);
    
    bb.putChar(ch); //store 2 byte unsigned value in byte buffer and reach 2     
    position forward //in buffer
    
    bb.order(ByteOrder.LITTLE_ENDIAN);
    
     bb.position(0);   //goto start of buffer again for reading
    
    ch=bb.getChar(); //retrieve 2 byte unsigned value from byte buffer
    
     i=(int) ch; //always store a 2-byte unsigned value (e.g.unsigned char) into      
     a 4-byte signed //datatype to avoid storing as 2’s compliment negative no.
    
      //now 4 byte integer ‘i’ contains a 2-byte unsigned +ve integer value for    
       processing
    
      System.out.println(“2 byte unsigned int value=”,i );
    

    完整代码见这里:program to read and store big and little endian

    【讨论】:

      猜你喜欢
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      相关资源
      最近更新 更多