[View]  [Edit]  [Lock]  [References]  [Attachments]  [History]  [Home]  [Changes]  [Search]  [Help] 

sample[LuaStudio] VSE-aNumber toString: base

[S8] Implement Number>>toString: base (using #printOn:base: VSE algorithm)

! String class methodsFor: #instantiation !
digitValue: anInteger
        "Answer the character representation
         of the digit anInteger."

    anInteger >= 0
        ifTrue: [
            anInteger < 10
                ifTrue: [ ^ '0123456789' at: anInteger + 1 ].
            anInteger <= 35
                ifTrue: [  ^self fromCharCode: anInteger + 55] ].
    ^self error: 'digitValue not in range 0..35'.! ! 

! Number methodsFor: #arithmetic !
toString: b
	" Return a string representation of the receiver expressed in base b "

	| stream |
	(b < 2 or: [ b > 32 ]) ifTrue: [
		^self error: 'base not between 2 and 32'
	].
	stream := '' writeStream.
	self printOn: stream base: b showRadix: true.
	^stream contents! !

! Number methodsFor: #private !
printOn: aStream base: anInteger showRadix: aBoolean
	"Append the ASCII representation of
	 the receiver with radix b to aStream;
	 if aBoolean is true, include the radix
	 prefix."

    | aString tempStream n |
    n := self.
	n < 0
        ifTrue: [
            aStream nextPut: $-.
            n := self negated ].
    ( anInteger = 10 or: [ aBoolean not ] )
        ifFalse: [ "print radix"
            anInteger printOn: aStream base: 10 showRadix: false.
            aStream nextPut: $r ].
	aString := ''.
    tempStream := aString writeStream.
    [ anInteger <= n ]
        whileTrue: [
            tempStream nextPut: (String digitValue: n \\ anInteger).
            n := n // anInteger ].
    aStream nextPut: (String digitValue: n).
    n := tempStream position.
    aString := tempStream contents.
    [ n = 0 ]
        whileFalse: [
            aStream nextPut: (aString at: n).
            n := n - 1 ]! !


	# #print: ' express 4 in base 1 '.
	[ 	4 toString: 1.
		# #print: #fail. 
	] on: Error do: [:ex | # #print: #ok ].
	
	# #print: ' express 1500000 in base 33 '.
	[ 	1500000 toString: 33.
		# #print: #fail. 
	] on: Error do: [:ex | # #print: #ok ].
	
	# #print: ' express 26 in hexa '.
	(26 toString: 16) = '16r1A' ifTrue: [
	# #print: #ok ] ifFalse: [ # #print: #fail 
	]!