[Q][Smalltalk][hex] converting binary to hex

Ken G. Brown kbrown at tnc.ab.ca
Tue Mar 19 14:37:05 UTC 2002


At 16:23 +1200 on 2002/03/19,  Richard A. O'Keefe is rumored to have written:
>In that case, let's not waste time and space making a string.
>
>     hex := '0123456789ABCDEF'.
>     aByteArray do: [:each |
>	aStream nextPut: (hex at: each // 256 + 1).
	aStream nextPut: (hex at: each \\ 256 + 1)].

This is what I tried:

aByteArray _ ByteArray new: 10 .
aByteArray at: 1 put: 10; at: 2 put: 15; at: 3 put: 16.
aString _ String new: 20.
aStream _ WriteStream on: aString. 
hex := '0123456789ABCDEF'.
     aByteArray do: [:each | aStream nextPut: (hex at: each // 256 + 
1). aStream nextPut: (hex at: each \\ 256 + 1)].

It appears to break when the byte value gets bigger than 15. Or did I 
do something incorrectly?
Thx
   Ken

At 16:23 +1200 on 2002/03/19,  Richard A. O'Keefe is rumored to have written:
>"Ken G. Brown" <kbrown at tnc.ab.ca> wrote:
>	Where would I find a routine to convert a ByteArray from binary to hex?
>	ie.[sic.]
>	#(10 15 16) would end up as #('0A' '0F' '10')
>	I figure it must be in there somewhwere but I cannot find it.
>
>Try
>     hex := '01234567789ABCDEF'.
>     aByteArray collect: [:each|
>	hi := each // 16 + 1.
>	lo := each \\ 16 + 1.
>         (hex copyFrom: hi to: hi), (hex copyFrom: lo to: lo)]
>
>	The intent is to convert a stream of bytes going to a file into
>	their hex equivalent without the 16r stuff like when you evaluate:
>
>In that case, let's not waste time and space making a string.
>
>     hex := '0123456789ABCDEF'.
>     aByteArray do: [:each |
>	aStream nextPut: (hex at: each // 256 + 1).
>	aStream nextPut: (hex at: each \\ 256 + 1)].




More information about the Squeak-dev mailing list