How can I represent a string as an integer in C for a hash table?

  • Thread starter Thread starter unknown_2
  • Start date Start date
  • Tags Tags
    Integers Strings
Click For Summary
To represent a string like "thisISastring" as an integer key for a hash table using the division method, it's essential to consider the size of the hash. For fewer than 50 records, using the ASCII value of the first character may suffice. For larger datasets, incorporating multiple characters can improve uniqueness; for instance, using the ASCII values of the first two characters. Adjusting the ASCII values by subtracting 32 can normalize the range to 0-94, which is beneficial for standard "typeable" strings. In C, strings are arrays of characters, allowing each character to be treated as a 1-byte integer, typically ranging from 0-255. This approach can help in effectively generating hash keys from string inputs.
unknown_2
Messages
28
Reaction score
0
hey, I've hit a bump in the road here. I'm trying to build code for a hash table out of my textbooks pseudo code, and I'm not quite sure how I'd represent a string of characters such as "thisISastring", as an integer for my key variable. I'm using division method if that helps at all. I know the function atoi(), but that's only for number strings right?

thanks,
 
Technology news on Phys.org
First, you probably want to know the size of your hash. If you need in the ballpark of 50 records or less, you can take the ASCII value of the first character in the string, and that's probably ok. If you need more, take the ASCII values of the first two characters, etc.

If it's a standard "typeable" string, you might want to take the ASCII value and subtract 32, which means each "typical" character would be in the range of 0-94. If that was ok, and you wanted a bigger hash, you could take the ASCII value of the 1st character minus 32, and add it to, say, 95 times the ASCII value of the 2nd character minus 32. And so on.

If I remember my C correctly, a string is simply an array of characters, and you can simply treat a single character as though it were a 1-byte integer (IE, it's already an integer, probably 0-255).

DaveE
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

Replies
55
Views
6K
  • · Replies 34 ·
2
Replies
34
Views
4K
Replies
1
Views
8K
  • · Replies 6 ·
Replies
6
Views
6K
Replies
2
Views
1K
  • · Replies 4 ·
Replies
4
Views
6K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
6K
  • · Replies 20 ·
Replies
20
Views
3K