Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Hello, I was wondering if I could get this code explained to me. Also if there was anything incorrect, if it could be fixed. If

Hello, I was wondering if I could get this code explained to me. Also if there was anything incorrect, if it could be fixed. If a sample output is possible, can it be done?
Thank you!
#include
#include
#define MAXSTRING 100
/*
* USAGE:
* gcc hashHarness.c -o hashX
* ./hashX < inputFile.txt
*/
/*
*djb2
* this algorithm (k=33) was first reported by dan bernstein many years ago in comp.lang.c.
* another version of this algorithm (now favored by bernstein) uses
* xor: hash(i) = hash(i - 1) * 33 ^ str[i];
* the magic of number 33 (why it works better than many other constants, prime or not)
* has never been adequately explained.
*
* ref:http://www.cse.yorku.ca/~oz/hash.html
*/
unsigned long hashDJB2(char *str)
{
unsigned long hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
/*
* K&R's simple but ...
* This hash function appeared in K&R (1st ed) but at least the reader was warned:
* "This is not the best possible algorithm, but it has the merit of extreme simplicity."
* This is an understatement; It is a terrible hashing algorithm, and it could have been
* much better without sacrificing its "extreme simplicity." [see the second edition!]
* Many C programmers use this function without actually testing it, or checking something
* like Knuth's Sorting and Searching, so it stuck. It is now found mixed with otherwise
* respectable code, eg. cnews. sigh.
*
*/
unsigned long hashKR(char *str)
{
unsigned int hash = 0;
int c;
while ((c = *str++))
hash += c;
return hash;
}
int main(int argc, char *argv[])
{
char *buffer;
int bufferlen = MAXSTRING;
unsigned long newHash;
unsigned long newKRhash;
buffer = malloc(MAXSTRING);
if (buffer == NULL)
{
printf("Bad malloc bye! ");
return 1;
}
while (fgets(buffer, bufferlen, stdin))
{
// printf("data in:%s", buffer);
if (ferror(stdin))
{
printf("Error on stdin ");
break;
}
/*
* Hash 'em up - commences!
*/
newHash = hashDJB2(buffer);
newKRhash = hashKR(buffer);
printf("hash:%016lx:%016lx:%s", newHash, newKRhash, buffer);
}
printf(" Done! ");
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Databases And Python Programming MySQL MongoDB OOP And Tkinter

Authors: R. PANNEERSELVAM

1st Edition

9357011331, 978-9357011334

More Books

Students also viewed these Databases questions

Question

2. Do you find change a. invigorating? b. stressful? _______

Answered: 1 week ago