temp_
temp_

Reputation: 1317

Flutter/Dart List with set size and bit shifting question

I'm writing to a piece of hardware using bluetooth and need to format my data in a specific way.

When I get the value from the device I have do a little bit shifting to get the correct answer. Here is a breakdown of the values I am getting back from the device.

byte[1] = (unsigned char)temp;
byte[2] = (unsigned char)(temp>>8);
byte[3] = (unsigned char)(temp>>16);
byte[4] = (unsigned char)(temp>>24);

It is a List with a size of 4. A real world example would be this:

byte[1] = '46';
byte[2] = '2';
byte[3] = '0';
byte[4] = '0';

This should work out to be

558

My working code to get this is:

  int _shiftLeft(int n, int amount) {
    return n << amount;
  }
  int _getValue(List<int> list) {
    int temp;
    temp = list[1];
    temp += _shiftLeft(list[2], 8);
    temp += _shiftLeft(list[3], 16);
    temp += _shiftLeft(list[4], 24);
    return temp;
  }

The actual list I get back from the device is quite large but I only need values 1-4.

This works great and gets me the correct value back. Now I have to write to the device. So if I have a value of 558, I need to build a list of size 4 with the same bit shifting but in reverse. Following the exact method above but in reverse. What is the best way to do this?

Basically if I pass a method a value of '558' I need to get back a List<int> of [46,2,0,0]

Upvotes: 1

Views: 764

Answers (1)

kaboc
kaboc

Reputation: 844

You can get only the lower 8 bits by the bitwise AND operation & 255 (or & 0xFF). Just combining this with bit shifting will do.

int _shiftRight(int n, int amount) {
  return n >> amount;
}

List<int> _getList(int value) {
  final list = <int>[];
  list.add(value & 255);
  list.add(_shiftRight(value, 8) & 255);
  list.add(_shiftRight(value, 16) & 255);
  list.add(_shiftRight(value, 24) & 255);
  return list;
}

It can be simplified using for as follows:

List<int> _getList(int value) {
  final list = <int>[];
  for (int i = 0; i < 4; i++) {
    list.add(value >> i * 8 & 255);
  }
  return list;
}

Upvotes: 1

Related Questions