+redef class Int
+ # A big-endian representation of self.
+ #
+ # ~~~
+ # assert 1.to_bytes.hexdigest == "01"
+ # assert 255.to_bytes.hexdigest == "FF"
+ # assert 256.to_bytes.hexdigest == "0100"
+ # assert 65535.to_bytes.hexdigest == "FFFF"
+ # assert 65536.to_bytes.hexdigest == "010000"
+ # ~~~
+ #
+ # For 0, a Bytes object with single nul byte is returned (instead of an empty Bytes object).
+ #
+ # ~~~
+ # assert 0.to_bytes.hexdigest == "00"
+ # ~~~
+ #
+ # `Bytes::to_i` can be used to do the reverse operation.
+ #
+ # ~~~
+ # assert 1234.to_bytes.to_i == 1234
+ # ~~~
+ #
+ # Require self >= 0
+ fun to_bytes: Bytes do
+ if self == 0 then return "\0".to_bytes
+ assert self > 0
+
+ # Compute the len (log256)
+ var len = 1
+ var max = 256
+ while self >= max do
+ len += 1
+ max *= 256
+ end
+
+ # Allocate the buffer
+ var res = new Bytes.with_capacity(len)
+ for i in [0..len[ do res[i] = 0u8
+
+ # Fill it starting with the end
+ var i = len
+ var sum = self
+ while i > 0 do
+ i -= 1
+ res[i] = (sum % 256).to_b
+ sum /= 256
+ end
+ return res
+ end
+end
+