flutterdartbluetooth-lowenergy

How does an "int" represent a byte (8 bits) when an int is normally 32 or 64 bits?


I'm curious how in the Dart programming language a byte is represented by the int type. I am confused because in Java, which Dart closely resembles, an int is 32 bits.

I ask because the leading flutter ble library, Flutter Blue, seems to handle List<int> while handling the ble bytes.

However according to the official documentation: https://flutter.dev/docs/development/platform-integration/platform-channels#codec Uint8List is used - which is what makes sense as the byte[] equivalent.

It seems the unsigned 8 bit integers are just then converted to a 32 bit signed int going from Uint8List -> List<int> ? i.e. decimal 2 is then converted from 00000010 to 00000000000000000000000000000010?

It seems this has ramifications if one would like to write a byte stream. Would one need to cast the int's to Uint8's?


Solution

  • The Dart int type is a 64-bit two's complement number—except when compiled for the web, there it's a 64-bit floating point number with no fractional part (a JavaScript number which has an integer value).

    How those values are represented internally depends on optimizations, they can be represented as something smaller if the runtime system knows for sure that the value will fit. That's an optimization, you won't be able to tell the difference.

    A "byte" value is an integer in the range 0..255. You can obviously store a byte value in an int.

    The most efficient way to store multiple bytes is a Uint8List, which implements List<int>. It stores each element as a single octet. When you read a value out of a Unit8List, its byte value is represented by an int. When you store an int in the Uint8List, only the low 8 bites are stored. So it does expanding reads and truncating writes to move values between an octet and a 64-bit value.