Skip to content

Convert string to specific int

I am creating foreground notification with ID like so:
startForeground(1, notification)

When initialising the service I am sending to it some string (ex: Hello). I wish that the service and notification will be bind to this string so I wish to use it as my id. So, how can I convert string to unique ID? For example the word “Hello” will always generate 123 And the word Bye will always generate 456.



That sounds like you want a “Hash Code”; a value derived from some other information that is (hopefully, but not always) unique.

There are a lot of different algorithms available to do this and if you search for “hash code” you will find lots of them (especially in the security domain; sha, md5 etc)

It sounds like you may not really need to get that complex (some of the more secure and “unique” hash code algorithms can be slow to calculate).
Is there any reason why you can’t use the string itself?

String comparison may be slow, but maybe not as slow as a good hash. Also you might be able to use a Hash Table if you need a faster “lookup”.. hashmap

Anyway, if you really do need a hash code from a string, a quick search found this (which looks reasonable) Sam Clarke; Kotlin Hash Strings

1 People found this is helpful