Hi, I’m looking at converting numeric characters to integers i.e. #\1 to 1 (not 49 which is the character code) I have not seen a standard function for this so I have tried 2 alternative appraches to this (define (char->int c)
(- (char->integer c) 48))
and (define (char->int c)
(string->number (~a c)))
is one of these methods the ‘preferred’ way, or is there another way?
@mark.warren (string->number)
I think
Does that work on single characters
I don’t think so, but you can make a string out of one character
That’s what (~a c) does
(string->number (string #\1))
Yeah, that’s what my second approach does, but using ~a
instead of string
Yes. It’s not that frequent to need exactly one character as an integer, so I guess any of those approaches are good. The only thing would be about performance if it goes into a really tight loop or something.
@mark.warren the first one is the way it’s usually done
@samth Thanks, I’m just doing a checksum test on a numeric string, the check it’s very basic but it needs you to multiply each digit of the number by a weight and then sum them.
I knew it :smile:
I was trying to find some usecase, and this is exactly what came to my mind first :stuck_out_tongue:
@jerome.martin.dev Hehe
I think you can also do that with a (for) loop … something like (in-char)
nope, (in-string)
Yeah, that’s how I’m doing it, I do a string->list
on the string which gives me the characters, which I then needed to convert to integer values.
(define (char->int c)
(- (char->integer c) 48))
(define (check-remainder check-number)
(modulo (for/sum ([weight (range 10 1 -1)]
[digit (string->list check-number)])
(* weight (char->int digit)))
11))
what I mean is that you can probably make a one-liner: (for/sum ([c (in-string "1234")])
(- (char->integer c) 48))
oh yeah, right
you used that :stuck_out_tongue:
nevermind my comment then, I was too slow!
so yeah the only difference is that I use (in-string) instead of (string->list) which has an optimization in the for loop
Thanks for the help
@jerome.martin.dev I’ll give the in-string way a go
@mark.warren if the indended use is for byte streams, how about using bytes directly?
@shu—hung It is an input from a user, so it’s a string, I could convert it to a byte string.