I was making some code to put my tiles into a mutableMap of the tiles and their coords based on their tags I manually put in, and I found that char.toString().toInt() returns the character as a number like expected, but for some reason, char.toInt() returns it as a number 48. Why does it do this? Here's my code that shows this:
board.forEach { tile: View ->
var x: Int? = null
var y: Int? = null
tile.tag.toString().toCharArray().forEach { c: Char ->
if(c.isDigit() && x == null) x = c.toInt() else if(c.toString() != "," && y == null) y = c.toString().toInt()
}
tileMap[Coord(x!!, y!!)] = tile
}
I have some code that prints the tile's tag (which is what is used to determine the Coords for the tileMap) and the tile's Coords' x & y values (from the tileMap) whenever you tap on them. So for example, when I tap on a tile 1 to the right of the bottom left corner, I expect to see "1,0 | (X: 1, Y: 0)" but instead (when both x and y are defined by char.toInt()) I get "1,0 | (X: 49, Y: 48)"
A tile at Coords x=1, y=2 (tag = "1,2") when put into the tileMap would have its coords in the map input like this:
| tileMap X definition | tileMap Y definition | Coords from tileMap | Actual Coords(from its tag) |
|:----:|:------:|:------:|:-----:|
| char.toInt() | char.toInt() | "49, 50" | "1, 2" |
| char.toString().toInt() | char.toString().toInt() | "1, 2" | "1, 2" |
| char.toInt() | char.toString().toInt() | "49, 2" | "1, 2" |
Why does char.toInt() (and char.code) return 48 more than the number?
CodePudding user response:
Because computers generally process numbers, each character is internally represented as a number. When using ASCII character encoding, each character is a number in 0-127 range. Unicode is more complicated, but let's stick to ASCII for simplicity.
If we look into the ASCII table, we can see that for example the letter A is internally stored as a decimal value 65. Digit 0 is stored as 48, digit 1 as 49 and so on.
char.toInt() doesn't mean: "interpret this character as a digit and return it as integer". It means: "return an internal numeric value for this character". And as we can see in the ASCII table, internal representation of 0 is 48.
