Your example contains 2 wrapper RNGs, their next()
functions return wrapped.next().littleEndian
and .bigEndian
respectively, and you are comparing the resulting byte streams. And of course they are different - big/little endian values do have different byte orders.
But that's not the issue - I'm saying that you don't need .littleEndian
or .bigEndian
at all to serialise or deserialise a byte stream.
Let's say the RNG gives your LE machine a binary integer which happens to have the numeric value 36029346783166592. Let's inspect its bytes:
// On a LE machine
func didGenerate(value: UInt64) {
withUnsafeBytes(of: value) { print(Array($0)) }
// [128, 0, 128, 0, 128, 0, 128, 0] <- byte sequence we want to preserve.
print(value)
// 36029346783166592 <- how this machine interprets it as a number. We don't really care about this; it's basically arbitrary.
}
That byte stream is the thing we actually want to preserve - not the number 36029346783166592. So I write those bytes in to a buffer, in the order they are, and pass them over to a BE machine. Like I showed in the ReplayRNG
, when the BE machine reads, it just loads those exact bytes in to UInt64
, except now:
// On a BE machine
func didRead(value: UInt64) {
withUnsafeBytes(of: value) { print(Array($0)) }
// [128, 0, 128, 0, 128, 0, 128, 0] <- correct byte sequence! That's what we want!
print(value)
// 9223512776490647552 <- interpreted as a different numeric value, but who cares?
}
This really illustrates the choice that you have: you can have the same bytes, or the same numeric values, but not both. That is just inherent in the fact that the two machines use different byte patterns to represent the same number.
In your case, your function talks about preserving bytes, so it's a byte-stream. In OP's case, it's a windspeed reading from a sensor -- clearly, a numeric value, so endianness is relevant for OP but not for your use-case.
The fact that byte streams are endianness-independent is a major advantage. For example, it means that UTF-8 is endianness-independent while UTF-16 comes in big/little variants.