0
0
Kotlinprogramming~10 mins

Number literal formats (underscore, hex, binary) in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Number literal formats (underscore, hex, binary)
Start
Read number literal
Check for underscores
| Yes
Ignore underscores
Check for prefix
Parse as hex
Parse as decimal
Store value
End
The program reads a number literal, ignores underscores, detects if it's hex or binary by prefix, parses accordingly, and stores the value.
Execution Sample
Kotlin
val a = 1_000
val b = 0x1F
val c = 0b1010
Defines three numbers: decimal with underscores, hexadecimal, and binary.
Execution Table
StepLiteralUnderscores RemovedPrefix DetectedParsed ValueAction
11_0001000None1000Parsed as decimal
20x1F0x1F0x (hex)31Parsed as hexadecimal
30b10100b10100b (binary)10Parsed as binary
4----End of literals
💡 All literals processed and parsed to decimal values.
Variable Tracker
VariableInitialAfter Step 1After Step 2After Step 3Final
aundefined1000100010001000
bundefinedundefined313131
cundefinedundefinedundefined1010
Key Moments - 3 Insights
Why do underscores not affect the number's value?
Underscores are ignored during parsing as shown in step 1 of the execution_table where '1_000' becomes '1000'. They are just for readability.
How does the program know to parse '0x1F' as hexadecimal?
The prefix '0x' signals hexadecimal parsing, as shown in step 2 of the execution_table.
What happens if a number starts with '0b'?
It is parsed as binary, like in step 3 where '0b1010' becomes decimal 10.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the parsed value of '0x1F' at step 2?
A31
B1F
C0x1F
D15
💡 Hint
Check the 'Parsed Value' column in row for step 2.
At which step does the program remove underscores from the literal?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Underscores Removed' column in the execution_table.
If the literal was '0b1101_0010', how would the parsed value change compared to '0b1010'?
AIt would be 210
BIt would be 162
CIt would be 10
DIt would be 11010010
💡 Hint
Binary '0b11010010' equals decimal 210, but underscores are ignored, so check binary to decimal conversion.
Concept Snapshot
Number literals can include underscores (_) for readability.
Hexadecimal numbers start with '0x' and use digits 0-9 and letters A-F.
Binary numbers start with '0b' and use digits 0 and 1.
Underscores are ignored when parsing.
All literals convert to decimal values internally.
Full Transcript
This example shows how Kotlin reads number literals with underscores, hexadecimal, and binary formats. First, underscores are removed to simplify the number. Then, the program checks if the number starts with '0x' for hex or '0b' for binary. It parses accordingly: hex numbers convert from base 16, binary from base 2, and others as decimal. The parsed values are stored as normal decimal numbers. This helps write numbers clearly without changing their value.