There shouldn't be any confusion as to how an int
can be used to represent bytes because it all comes down to bits and how you store and manipulate them.
For the sake of simplicity, let us assume that an int
is larger than a byte - an int is 32 bits, and a byte is 8 bits. Since, we are dealing with just bits at this point, you can see it is possible for an int to contain 4 bytes because 32/8 is 4 i.e. we can use an int to store bytes without loosing information.
It seems as those the unsigned 8 bit integers are just then converted to a 32 bit signed int going from Uint8List -> List ? i.e. decimal 2 is is then converted from 00000010 to 00000000000000000000000000000010?
You could do it that way, but from I said previously, you can store multiple bytes in an int.
Consider if you have the string Hello, World!
, which comes up to 13 bytes and you want to store these bytes in a list of int
s, given each int
is 32 bits; We only need to use 4 ints to represent this string because 13 * 8
is 104 bits, and four 32bit ints can hold 128 bits of information.
It seems this has ramifications if one would like to write a byte stream. Would need to cast the int's to Uint8's.
Not necessarily.
A byte stream consisting of the bytes 'H', 'e', 'l', 'l', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'
can be written into a data structure known as a Bit Array
. The bit array for the above stream would look like:
[01001000011001010110110001101100011011110010110000100000010101110110111101110010011011000110010000100001]
Or a list of 32 bit ints:
[1214606444,1865162839,1869769828,33]
If we wanted to convert this list of ints back to bytes, we just need to read the data in chunks of 8 bits to retrieve the original bytes. I will demonstrate it with this simply written dart program:
String readInts(List<int> bitArray) {
final buffer = StringBuffer();
for (var chunk in bitArray) {
for (var offset = 24; offset >= 0; offset -= 8) {
if (chunk < 1 << offset) {
continue;
}
buffer.writeCharCode((chunk >> offset) & 0xff);
}
}
return buffer.toString();
}
void main() {
print(readInts([1214606444,1865162839,1869769828,33]));
}
The same process can be followed to convert the bytes to integers - you just combine every 4 bytes to form a 32 bit integer.
Output
Hello, World!
Of course, you should not need to write such a code by yourself because dart already does this for you in the Uint8List
class