I’m teaching myself CIL and have been doing ok so far (just really started yesterday) but I have run into a problem I can’t really figure out. I’m prompting the user for an int (int32) and then storing it and converting it to a float and displaying it. However, whatever I enter comes out different as a float. Here is my code:
.assembly variables {}
.method public static void main() cil managed
{
.entrypoint
.maxstack 8
.locals init (float64)
ldstr "Enter a digit: "
call void [mscorlib]System.Console::WriteLine(string)
call int32 [mscorlib]System.Console::Read()
conv.r8
stloc.0
ldstr "as a float: "
call void [mscorlib]System.Console::WriteLine(string)
ldloc.0
dup
call void [mscorlib]System.Console::Write(float64)
stloc.0
ldstr "Stored in location 0"
call void [mscorlib]System.Console::WriteLine(string)
ldloc.0
conv.i4
call void [mscorlib]System.Console::WriteLine(int32)
call int32 [mscorlib]System.Console::Read() // to pause before closing window
pop
ret
}
I was just fooling around with CIL but figured I’d throw in my whole example for clarity. It compiles fine but when I type in 5 it returns 53 as the float AND the converted int32.
Can somebody please shed some light on what I’m doing wrong!
EDIT: Thanks to Marc Gravell I was able to figure it out. For those who are interested, here is the correct code:
.assembly variables {}
.method public static void main() cil managed
{
.entrypoint
.maxstack 8
.locals init (float64)
ldstr "Enter a digit: "
call void [mscorlib]System.Console::WriteLine(string)
call string [mscorlib]System.Console::ReadLine()
call int32 [mscorlib]System.Int32::Parse(string)
conv.r8
stloc.0
ldstr "as a float: "
call void [mscorlib]System.Console::WriteLine(string)
ldloc.0
dup
call void [mscorlib]System.Console::Write(float64)
stloc.0
ldstr "Stored in location 0"
call void [mscorlib]System.Console::WriteLine(string)
ldloc.0
conv.i4
call void [mscorlib]System.Console::WriteLine(int32)
call int32 [mscorlib]System.Console::Read() // to pause before closing window
pop
ret
}
Console.Readreturns a Unicode code-point, or -1 for EOF. 53 is the code-point of the character (not integer)'5'.You could perhaps use
Console.ReadLineandint.Parse.