binary-coded decimal

Monkey Forums/Monkey Programming/binary-coded decimal

bitJericho(Posted 2015) [#1]
Hey, I need to convert a number between 0 and 255 into it's component numbers. For example, 255 would be 3 values, 2, 5 and 5, or 13 would give me the values 0, 1 and 3. I'm not really sure how to do it mathematically and I couldn't find any examples of it. Any ideas? I tried just converting it to a string and pulling the characters from the string but that isn't working properly it seems. This gives weird results in 77a. Any tips?

Strict
Function Main:Int ()

	Local test:String = String(253)
	Print test[1]

	Return 0
End



Danilo(Posted 2015) [#2]
test[x] returns the character number at position x.

You need to use string slicing to extract the string.
Strict
Function Main:Int ()

	Local test:String = String(253)
	
	test = ("000" + test)            ' make sure the string is at least 3 chars long
	test = test[test.Length - 3 ..]  ' and take the last 3 chars
	
	For Local i:Int = 0 Until test.Length
		Print test[i .. i + 1]
	Next

	Return 0
End


Strict
Function Main:Int ()

	Local test:String = "000" + String(253)
		
	For Local i:Int = test.Length - 3 Until test.Length
		Print test[i .. i + 1]
	Next

	Return 0
End



SLotman(Posted 2015) [#3]
You know that 255 in binary is 11111111b and not 2,5,5... right?

Now if you want to separate each number, just divide it:
255/100 = 2
255 - (2*100) = 255 - 200 = 55
55 / 10 = 5
255 - (2*100) - (5*10) = 255-200-50 = 5

Got it?


Samah(Posted 2015) [#4]
Local num:Int = 255
Local digit1:Int = num/100
Local digit2:Int = (num/10) Mod 10
Local digit3:Int = num Mod 10

Should do it.
Disclaimer: I haven't tried compiling this.


bitJericho(Posted 2015) [#5]
That's exactly what I was looking for, I can't believe how simple that was. Thanks!


Gerry Quinn(Posted 2015) [#6]
Just with regard to your string chopping idea, the problem you had was that string indexing - as distinct from slicing - returns a character code rather than a string.

So if you have str:String = "ABC" and you want a string "B", either of these will work:

str[ 1 .. 2 ]

or

String.FromChar( str[ 1 ] )