help-smalltalk
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Help-smalltalk] CharacterArray to Number conversion (hexadezimal)


From: Markus Fritsche
Subject: [Help-smalltalk] CharacterArray to Number conversion (hexadezimal)
Date: Fri, 27 Dec 2002 02:50:36 +0100
User-agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.3a) Gecko/20021212

Hi!

A little code snippet allowing to interpret a string as a hexadezimal number. I couldn't work out a more standard name, suggestions?

Regards, Markus

--
http://reauktion.de/archer/
Number class methodsFor: 'converting'!
readHexFrom: aStream
    "Answer the number read from the rest of aStream, converted to an
     instance of the receiver. If the receiver is number, the class of the
     result is undefined -- but the result is good."
    | value ch scale |
    value := 0.
    scale := (aStream peekFor: $-) ifTrue: [ -1 ] ifFalse: [ 1 ].

    [ aStream atEnd ifTrue: [^self coerce: value].
      (ch := aStream next) isHexDigit ] whileTrue: [
         value := ch digitValue * scale + (value * 16).
    ].
    ch = $. ifFalse: [aStream skip: -1. ^value].

    [ aStream atEnd ifTrue: [^self coerce: value].
      (ch := aStream next) isHexDigit ] whileTrue: [
         scale := scale / 16.
         value := ch digitValue * scale + value.
    ].

    aStream skip: -1.
    ^self coerce: value
! !
        
!Character methodsFor: 'testing'!

isHexDigit
    "True if self is a 0-F digit"
        ^(self isDigit) or: [
                #($A $B $C $D $E $F) includes: self
        ]
! !

!CharacterArray methodsFor: 'converting'!

numberFromHex
    "Parse a Number from the receiver until the input character is invalid
     and answer the result at this point"

    ^Number readHexFrom: (ReadStream on: self)
! !

reply via email to

[Prev in Thread] Current Thread [Next in Thread]