1

I'm learning Mozart and I have a question, Does anyone knows how to convert a Integer to an Hexadecimal without the manual-mathematical table conversion. Is there any included function/module to do that? I know how to convert the other way:

 {String.toInt "0x2d7"} %% Hex to Int
 {String.toInt "052"}   %% Octal to Int
 {String.toInt "0b101010"} %% Binary to Int

Thank you in advance.

1 Answers1

0

I don't think the language has anything like a function or module to convert from decimal to hex. Anyway, here's a possible solution. It may not be very efficient or elegant, but you can see some of the basic ideas the language handles.

declare
    proc {DecConv X F ?R} % X:integer; F: b:binary, o:octal, or x:hexa; R:Result.
        fun {DivList N F}
            if N =< 0 then nil
            else N mod F|{DivList (N div F) F}
        end
    end Rs in
    if {Int.is X} then
        case F
        of b then Dl={List.reverse {DivList X 2}} in
            Rs={Append "0b" {FoldR Dl fun {$ X Xr}
                                          if X==0 then 48|Xr else 49|Xr end
                                      end nil}}
        [] o then Dl={List.reverse {DivList X 8}} in
            Rs={Append "0" {FoldR Dl fun {$ X Xr} {Int.toString X}.1|Xr end nil}}
        [] x then Dl={List.reverse {DivList X 16}} in
            Rs={Append "0x" {FoldR Dl fun {$ X Xr}
                                          if X==10 then &A|Xr
                                          elseif X==11 then &B|Xr
                                          elseif X==12 then &C|Xr
                                          elseif X==13 then &D|Xr
                                          elseif X==14 then &E|Xr
                                          elseif X==15 then &F|Xr
                                          else {Int.toString X}.1|Xr
                                          end
                                      end nil}}
        else raise error_Enter_Format(F) end
        end
    else raise error_Should_be_Int(X) end
    end
    R={String.toAtom Rs}
end

Try to run this code in Mozart by selecting it and after that holding down the Ctrl key, then hitting the dot key and then the R key (to feed region). After this you can feed any of the next lines with Ctrl . Ctrl L (to feed line):

{Browse {DecConv 123 b}} %% '0b1111011'
{Browse {DecConv 123 o}} %% '0173'
{Browse {DecConv 123 x}} %% '0x7B'

As you will see the answer is an atom. You can also use the function {Atom.toString +A ?S} to convert the atom A to the string S. I hope any of this is useful for you.

rbi
  • 1
  • 1