DEV Community

kyorohiro (kiyohiro kawamura)
kyorohiro (kiyohiro kawamura)

Posted on

Dart's Network Byte Order

This section explains network byte orders.
There is no special problem when storing one byte of data in memory.

import 'dart:typed_data' show Uint8List;

String toHex(Uint8List buffer) {
  const List<String> vv = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
    var b = StringBuffer();
    for (var i = 0; i < buffer.length; i++) {
      var v = buffer[i];
      var v1 = (v >> 4) & 0xF;
      var v2 = v & 0xF;
      b.write('${vv[v1]}${vv[v2]}');
    }
    return b.toString();
}

main() async {
  var input = <int>[0x00, 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f];  
  var buffer = Uint8List(16);
  for(var i=0;i<input.length;i++){
    buffer[i] = input[i] & 0xFF;
  }
  print(toHex(buffer));
}
Enter fullscreen mode Exit fullscreen mode

When this is executed, it will output data such as 000102030405060708090a0b0c0d0e0f.

However, the problem is how to record 2 bytes of short data, 4 bytes of int data
etc. should be recorded in memory...

There are several recording methods, but two are the most common.

  • Big Endian
    When 0x1234 is recorded in memory, it is recorded as [0x12,0x34].

  • Little endian
    When 0x1234 is recorded in memory, it is recorded as [0x34,0x12].

Try to store it in little-endian format

main() async {
  var input = 0x1234;
  var buffer = Uint8List(2);

  //print(((input>>8) & 0xFF).toRadixString(16)); --> 12
  //print((input & 0xFF).toRadixString(16)); --> 34
  buffer[0] = input & 0xFF;
  buffer[1] = (input>>8) & 0xFF;
  print(toHex(buffer));
}
Enter fullscreen mode Exit fullscreen mode

If it is little-endian, it should be displayed in the order 0x34 0x12.
If it is big-endian, it should display 0x12 0x32 in that order.

When we run this, it returns 3412, so we have successfully stored the data as little-endian.

Try to store it in big-endian format


main() async {
  var input = 0x1234;
  var buffer = Uint8List(2);

  //print(((input>>8) & 0xFF).toRadixString(16)); --> 12
  // print((input & 0xFF).toRadixString(16)); --> 34
  buffer[0] = (input>>8) & 0xFF;
  buffer[1] = input & 0xFF;
  print(toHex(buffer));
}

Enter fullscreen mode Exit fullscreen mode

This will return 1234, so we have successfully stored the data in big-endian format.

Communication Protocols are Big Endian

In this article, we will implement DNS which is described in RFCs. In these protocols, data is exchanged in big-endian unless otherwise stated.

Top comments (0)