Variable-length quantity: Difference between revisions

→‎{{header|TXR}}: Replace with carray based answer, which directly meets requirements.
m (→‎{{header|Haskell}}: Simplified one function)
(→‎{{header|TXR}}: Replace with carray based answer, which directly meets requirements.)
Line 1,782:
=={{header|TXR}}==
 
TXR's <code>carray</code> type, closely associated with the Foreign Function Interface, has functions for converting between integers and foreign arrays. The arrays can use any element type. The integer is stored in big endian order, and "right justified" within the buffer, so that its least significant byte is aligned with the least significant byte of the last element of the array.
In TXR, the preferred way to render data into octets is to convert it to a character string. Character strings are Unicode, which serializes to UTF-8 when sent to text streams.
 
Two representations are supported: unsigned and signed. The unsigned representation takes only non-negative integers. It is a straightforward pure binary enumeration. The signed representation uses twos complement. The most significant byte of the array representation is in the range 80-FF if the value is negative, otherwise in the range 0 to 7F. This means that in some cases, a zero byte has to be added.
<lang txrlisp>;; show the utf8 bytes from byte stream as hex
(defun put-utf8 (str : stream)
(set stream (or stream *stdout*))
(for ((s (make-string-byte-input-stream str)) byte)
((set byte (get-byte s)))
((format stream "\\x~,02x" byte))))
 
Interactive session:
;; print
(put-utf8 (tostring 0))
(put-line "")
(put-utf8 (tostring 42))
(put-line "")
(put-utf8 (tostring #x200000))
(put-line "")
(put-utf8 (tostring #x1fffff))
(put-line "")
 
<pre>1&gt; (carray-num #x200000)
;; print to string and recover
#&lt;carray 3 #&lt;ffi-type uchar&gt;&gt;
(format t "~a\n" (read (tostring #x200000)))
2&gt; (carray-get *1)
(format t "~a\n" (read (tostring #x1f0000)))</lang>
#(32 0 0)
 
3&gt; (carray-num #x1FFFFF)
Run:
#&lt;carray 3 #&lt;ffi-type uchar&gt;&gt;
 
4&gt; (carray-get *3)
<pre>\x30
#(31 255 255)
\x34\x32
5&gt; (num-carray *1)
\x32\x30\x39\x37\x31\x35\x32
\x32\x30\x39\x37\x31\x35\x31
2097152
6&gt; (num-carray *3)
20316162097151</pre>
 
=={{header|zkl}}==
543

edits