Get char codes or generate an integer from string

I want to generate an integer from a given string for select an item from an array as index.
The integer must be the same if given strings are the same.
But no matter what if the strings are different.

This can be done with hash code generation algorithms but I cannot find proper function in Hugo.
md5, sha and base64 are generating a hash string instead of an integer.

On the other hands, if can get char code from the given string, can make an integer by SUM or XOR.
However, it seems there is no function to get char code.

I’ve tried int but runtime failed for non-digit characters.

{{ $str := `Test String Sequence` }}
{{ $len := (len $str) }}
{{ range (seq $len)}}
    {{ $charStr := (substr $str . 1)}}
    <p>{{ $charStr }}{{ int $charStr }}</p>
{{ end }}

Is there any way to figure out?

{{ $s := "This is nuts!" }}

{{ $s = split $s "" }}
{{ $s = apply $s "printf" "%#x" "." }}
{{ $s = apply $s "int" "." }}
{{ $s = delimit $s "" }}

{{ $s }} --> 84104105115321051153211011711611533
1 Like
{{ $codeTable := newScratch }}
{{ $codeTable.Set `$` 36 }}
{{ $codeTable.Set `+` 43 }}
{{ $codeTable.Set `0` 48 }}
...
{{ $codeTable.Set `u` 252 }}
{{ $codeTable.Set `y` 253 }}
{{ $codeTable.Set `þ` 254 }}
{{ $itemCount := 16 }}
{{ $scratch := newScratch }}
{{ $scratch.Set "Sum" 0 }}
{{ $len := (len $str) }}
{{ range (seq 0 $len) }}
    {{ $char := (substr $str . 1) }}
    {{ $code := (int ($codeTable.Get $char)) }}
    {{ $sum := (int ($scratch.Get "Sum")) }}
    {{ $add := (int (add $sum $code)) }}
    {{ $scratch.Set "Sum" $add }}
{{ end }}
{{ $sum := (int ($scratch.Get "Sum")) }}
{{ $itemIndex := (int (mod $sum $itemCount)) }}

Your method:

{{ $str := "abc" }} --> 6
{{ $str := "cba" }} --> 6

You’re right.
In my case, the hash has not to be good quality because just selecting random color for distinting UIs.

XOR is good for that case. but there is not, again.
Even though really basic bit operation in computer systems.

You can implement the same thing with a lot less code.

{{ $s = split $s "" }}
{{ $s = apply $s "printf" "%#x" "." }}
{{ $s = apply $s "int" "." }}
{{ $s = apply $s "mod" "." 16 }}
{{ $index := 0 }}
{{ range $s }}
  {{ $index = add $index . }}
{{ end }}

Can you explain about the %#x?

https://pkg.go.dev/fmt

{{ $itemCount := 16 }}
{{ $scratch := newScratch }}
{{ $scratch.Set "Sum" 0 }}
{{ $split := split $str "" }}
{{ range $split }}
    {{ $code := (int (printf "%#x" .)) }}
    {{ $sum := (int ($scratch.Get "Sum")) }}
    {{ $add := (int (add $sum $code)) }}
    {{ $scratch.Set "Sum" $add }}
{{ end }}
{{ $sum := (int ($scratch.Get "Sum")) }}
{{ $itemIndex := (int (mod $sum $itemCount)) }}

It looks more stable.
Thanks.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.