Question regarding day 9
Closed this issue · 3 comments
Hi there,
I'm reading the solution of day 9 part A and I do not understand this line
sum += (cell - b'0') as usize + 1;
What is b'0'
?
I'm pretty new to Rust, and in this case I'm not finding anything in documentation.
...or I don't know where to look 😭
Thanks a lot!
Hi @ildede , b
is a byte constant prefix and specifies that the following value (char '0'
) should be interpreted as a u8
/byte value (48
). See more detailed discussion here.
OK!
And this is done because cell
is a byte too, and not u8
or other number.
Right?
If so its clear, thanks @GaurangTandon !
That's right.
I read the file as bytes, getting one byte for each character. A byte is a u8
, which is of course, also a number. See the ASCII table for a list of corresponding decimal numbers for each character byte.
In Rust:
'0'
is achar
b'0'
is au8
'0' as u8 == b'0'
- So
b'0'
is a short literal for the0
character byte.
Because bytes are numbers (u8
) you can do arithmetic on them. In this case, I wanted to convert each character into it's numeric value. Using the bytes directly doesn't work because the numbers will be offset by 48 (0
is 48, 1
is 49, 2
is 50...), so I have to subtract 48 from them.
Rather than subtracting 48
, I subtract b'0'
. This is of course the same, but b'0'
looks more logical than a random 48
number.
So, this converts a digit character into a numeric value: cell - b'0'
I could keep it an u8
, but I cast it to an usize
because that's the type I like to use in the rest of the code, hence: (cell - b'0) as usize
And this is done because cell is a byte too, and not u8 or other number.
In Rust a byte is the same as an u8
. So, cell
is a byte, which is also a number.