0

I am working on an application that communicates via ble. It takes the users inputted password and converts it to a byte list before sending it over to the ble device.

List<int> _passWordToByteList(int password) {
  List<int> ret = [];
  ret.add(password & 0xff);
  ret.add((password >> 8) & 0xff);
  ret.add((password >> 16) & 0xff);
  ret.add((password >> 24) & 0xff);

  return ret;
}

I've read the dart documentation multiple times but I can't seem to understand what the purpose of the operand is for and why we would need it to convert the password to a byte list.

  • `x & 0xff` will truncate `x` to the first 8 bits. Keep in mind that `0xff` is `11111111` in binary, and since `int` in dart is 64 bit numbers, it is really `00000000_00000000_00000000_00000000_00000000_00000000_00000000_11111111` . The `&` operator will compare the binary value of both operands and return a new number that has `1` bits in each position that both operands have a `1` bit. – mmcdon20 May 30 '22 at 02:30
  • duplicates: [What are bitwise shift (bit-shift) operators and how do they work?](https://stackoverflow.com/q/141525/995714), [what are bits and bitwise operations used for?](https://stackoverflow.com/q/22603263/995714), [What is masking? (Bitwise operators) (duplicate)](https://stackoverflow.com/q/46720026/995714) – phuclv May 30 '22 at 03:37

1 Answers1

1

BLE sends data over the air in bytes. This means that values larger than 255 have to be sent as series of bytes. BLE sends those bytes in little endian format. The code in your question is taking an int32 and converting it into a list of 4 bytes in little endian format.

The conversion can be done as in your example although the Dart language does offer libraries to help with this:

https://api.dart.dev/stable/2.16.1/dart-typed_data/dart-typed_data-library.html

Example of how to use this is at:

Convert int32 to bytes List in dart

ukBaz
  • 6,985
  • 2
  • 8
  • 31