3

I have a list of 32-bit unsigned integers:

  var unixTimestamps = [
    1573613134,
    1573623934,
    1573631134,
    1573659934,
    1573746334,
    1573731934,
    1573764334,
    1573789534,
    1573847134,
    1573933534,
    1573893934,
    1573980334,
    1574153134,
    1574178334
  ];

I would like to save these to a file.

The list needs to be written iteratively as it depends on the user's interaction with the app.

final file = await _localFile(filename);
for (var i=0; i<unixTimestamps.length; i++){
  file.writeAsBytesSync(unixTimestamps[i], mode: FileMode.append)
}

with

Future _localFile(String filename) async {
  final path = await _localPath();
  return File('$path/$filename');
}

Future _localPath() async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

When I read back the data from that file, I noticed that it's unsigned 8-bit integers. (Values are between 0 and 255)

Below is the readData script:

  Future readData(filename, i) async {
    try {
      final file = await _localFile(filename);
      List contents = await file.readAsBytesSync();
      return contents;
    } catch (e) {
      print(e);
      return 0;
    }
  }

Is there a way for files to be saved and read as 32 bit integers?

poultrynews
  • 591
  • 1
  • 7
  • 15
  • 1
    afaik, you should use int8 to write and read but you can cast data type while writing and reading, for example https://stackoverflow.com/a/57536472/2395656 – Tarık Yılmaz Dec 22 '19 at 19:36

1 Answers1

0

If you do not want to use standard solutions, you can use a non-standard approach to solving the problem.
Example of non-standard approach (easy to understand and easy to maintain):

void main() {
  var list32 = [0x40302010, 0x10203040];
  final bytes = toBytes(list32, 4);
  print(bytes);
  final newList32 = fromBytes(bytes, 4);
  print(list32);
  print(newList32);
}

List<int> toBytes(List<int> list, int size) {
  final result = <int>[];
  for (var i = 0; i < list.length; i++) {
    final value = list[i];
    for (var j = 0; j < size; j++) {
      final byte = value >> (j * 8) & 0xff;
      result.add(byte);
    }
  }

  return result;
}

List<int> fromBytes(List<int> list, int size) {
  if (list.length % size != 0) {
    throw ArgumentError('Wrong size');
  }

  final result = <int>[];
  for (var i = 0; i < list.length; i += size) {
    var value = 0;
    for (var j = 0; j < size; j++) {
      var byte = list[i + j];
      final val = (byte & 0xff) << (j * 8);
      value |= val;
    }

    result.add(value);
  }

  return result;
}

Result:

[16, 32, 48, 64, 64, 48, 32, 16]
[1076895760, 270544960]
[1076895760, 270544960]

P.S.

You can add an overflow check to both methods to check the correctness of the data if you need such a check.

mezoni
  • 10,684
  • 4
  • 32
  • 54