-USING: help.markup help.syntax math math.parser.private prettyprint
-namespaces make strings ;
+USING: byte-arrays help.markup help.syntax math
+math.parser.private prettyprint namespaces make sequences
+strings ;
+
IN: math.parser
ARTICLE: "number-strings" "Converting between numbers and strings"
HELP: #
{ $values { "n" real } }
{ $description "Appends the string representation of a real number to the end of the sequence being constructed by " { $link make } "." } ;
+
+HELP: bytes>hex-string
+{ $values { "bytes" sequence } { "hex-string" string } }
+{ $description "Converts a sequence of bytes (integers in the range [0,255]) to a string of hex numbers in the range [00,ff]." }
+{ $examples
+ { $example "USING: math.parser prettyprint ;" "B{ 1 2 3 4 } bytes>hex-string ." "\"01020304\"" }
+}
+{ $notes "Numbers are zero-padded on the left." } ;
+
+HELP: hex-string>bytes
+{ $values { "hex-string" sequence } { "bytes" byte-array } }
+{ $description "Converts a sequence of hex numbers in the range [00,ff] to a sequence of bytes (integers in the range [0,255])." }
+{ $examples
+ { $example "USING: math.parser prettyprint ;" "\"cafebabe\" hex-string>bytes ." "B{ 202 254 186 190 }" }
+} ;
+
+{ bytes>hex-string hex-string>bytes } related-words
{ 0.0 } [ "1e-100000" string>number ] unit-test
{ 1/0. } [ "0x1p300000" string>number ] unit-test
{ 0.0 } [ "0x1p-300000" string>number ] unit-test
+
+{ "deadbeef" } [ B{ 222 173 190 239 } bytes>hex-string ] unit-test
+{ B{ 222 173 190 239 } } [ "deADbeEF" hex-string>bytes ] unit-test
! Copyright (C) 2009 Joe Groff, 2013 John Benediktsson
! See http://factorcode.org/license.txt for BSD license.
USING: accessors byte-arrays combinators kernel kernel.private
-layouts make math math.private namespaces sbufs sequences
-sequences.private splitting strings strings.private ;
+layouts make math math.private sbufs sequences sequences.private
+strings strings.private ;
IN: math.parser
<PRIVATE
} cond ;
: # ( n -- ) number>string % ; inline
+
+: hex-string>bytes ( hex-string -- bytes )
+ dup length 2/ <byte-array> [
+ [
+ [ digit> ] 2dip over even? [
+ [ 16 * ] [ 2/ ] [ set-nth ] tri*
+ ] [
+ [ 2/ ] [ [ + ] change-nth ] bi*
+ ] if
+ ] curry each-index
+ ] keep ;
+
+: bytes>hex-string ( bytes -- hex-string )
+ dup length 2 * CHAR: 0 <string> [
+ [
+ [ 16 /mod [ >digit ] bi@ ]
+ [ 2 * dup 1 + ]
+ [ [ set-nth ] curry bi-curry@ bi* ] tri*
+ ] curry each-index
+ ] keep ;