Polynomial Hashing vs Cyclic Polynomial shifting for strings - c

I am using this function for cyclic shift:
int hashcyclic(char *p, int len)
{
unsigned int h = 0;
int i;
for (i = 0; i < len; i++)
{
h = (h << 5) | (h >> 27);
h += (unsigned int)p[i];
}
return h%TABLESIZE;
}
On a text file with around 20K lines (one word/line) total amount of collisions is 45187. On a text file with 40K+ lines (again, one word/line) there are 12922252 (!) collisions with the same algorithm.
With polynomial hashing:
int hashpoly(char *K)
{
int h = 0, a = 33;
for (; *K != '\0'; K++)
h = (a * h + *K) % TABLESIZE;
return h;
}
Now I'm getting around 25K collisions on the 20K word file and 901K collisions on the 40K word file(almost 12 times less than the cyclic shift).
My question is, does this make sense or is one of my implementations messed up? I was expecting cyclic to be the fastest for my strings (the 40K word file is a series of 8 letter words seperated by newline) but polynomial faces significantly less collisions.
int HashInsertPoly(Table T, KeyType K, InfoType I)
{
int i;
int ProbeDecrement;
i = hashpoly(K);
ProbeDecrement = p(K);
while (T[i].Key[0] != EmptyKey)
{
totalcol++;
T[i].Info.col++;
i -= ProbeDecrement;
if (i < 0)
i += TABLESIZE;
}
strcpy(T[i].Key, K);
insertions++;
/*T[i].Info = I;*/
return i;
}
The same HashInsert function applies to the hash with cyclic shift, except now I call hashcyclic instead of hashpoly

My hunch is that the variation in plain text words isn't high, and so the cyclic hash isn't chaotic enough.
Let's look at two strings "cat" and "dog".
cat
c 01100011
a 01100001
t 01110100
h starts at
00000000 00000000 00000000 01100011 (c)
and is then cycled to
00000000 00000000 00001100 01100000
then we add `a` to get
00000000 00000000 00001100 01100000
+ 01100001
= 00000000 00000000 00001100 11000001
which is then cycled to
00000000 00000001 10011000 00100000
then we add `t` to get
00000000 00000001 10011000 00100000
+ 01110100
= 00000000 00000001 10011000 10010100
we then return this number mod 41893 for 20810
Similarly, for dog
d 01100100
o 01101111
g 01100111
start:
00000000 00000000 00000000 01100100 (d)
cycled and added o:
00000000 00000000 00001100 11101111
cycled and added t:
00000000 00000001 10011110 01000111
ends up at 22269
Because the ASCII range is small, and the cycle algorithm uses the entire space of the unsigned int, it takes long strings to really push the hash into a completely different space. Especially the last character, which really dominates the final modulus operation.
Another way of looking at it: there's very little interaction with a 7-bit ASCII character and the previous 7-bit ASCII character after you shift 5 of those bits away and replace them with 0s, especially for shorter words.
Since the polynomial hash only uses the table size, it's chaotic "faster", even for smaller strings. It doesn't have to fill a whole int before it starts being really chaotic. A single ASCII character is much larger the table size.
That's my guess, anyway. I'd confirm this by checking to see which strings collide. My guess is strings of similar length are colliding the most with the cycle algorithm.

Related

getting values of void pointer while only knowing the size of each element

ill start by saying ive seen a bunch of posts with similar titles but non focus on my question
ive been tasked to make a function that receives a void* arr, unsigned int sizeofArray and unsigned int sizeofElement
i managed to iterate through the array with no problem, however when i try to print out the values or do anything with them i seem to get garbage unless i specify the type of them beforehand
this is my function:
void MemoryContent(void* arr, unsigned int sizeRe, unsigned int sizeUnit)
{
int sizeArr = sizeRe/sizeUnit;
for (int i = 0; i < sizeArr ; i++)
{
printf("%d\n",arr); // this one prints garbage
printf("%d\n",*(int*)arr); // this one prints expected values given the array is of int*
arr = arr + sizeUnit;
}
}
the output of this with the following array(int arr[] = {1, 2, 4, 8, 16, 32, -1};) is:
-13296 1
-13292 2
-13288 4
-13284 8
-13280 16
-13276 32
-13272 -1
i realize i have to specify somehow the type. while the printf wont actually be used as i need the binary representation of whatever value is in there (already taken care of in a different function) im still not sure how to get the actual value without casting while knowing the size of the element
any explanation would be highly appreciated!
note: the compiler used is gcc so pointer arithmetics are allowed as used
edit for clarification:
the output after formating and all that should look like this for the given array of previous example
00000000 00000000 00000000 00000001 0x00000001
00000000 00000000 00000000 00000010 0x00000002
00000000 00000000 00000000 00000100 0x00000004
00000000 00000000 00000000 00001000 0x00000008
00000000 00000000 00000000 00010000 0x00000010
00000000 00000000 00000000 00100000 0x00000020
11111111 11111111 11111111 11111111 0xFFFFFFFF
getting values of void pointer getting values of void pointer while only knowing the size of each element
Not possible getting values of void pointer while only knowing the size of each element.
Say the size is 4. Is the element an int32_t, uint32_t, float, bool, some struct, or enum, a pointer, etc? Are any of the bits padding? The proper interpretation of the bits requires more than only knowing the size.
Code could print out the bits at void *ptr and leave the interpretation to the user.
unsigned char bytes[sizeUnit];
memcpy(bytes, ptr, sizeUnit);
for (size_t i = 0; i<sizeof bytes; i++) {
printf(" %02X", bytes[i]);
}
Simplifications exist.
OP's code void* arr, ... arr = arr + sizeUnit; is not portable code as adding to a void * is not defined by the C standard. Some compilers do allow it though, akin to as if the pointer was a char pointer.

Overwrite variables while linking c files

I have two files:
fir.c
int x = 7;
int y = 5;
int main()
{
p2();
printf("%d\n", x);
return 0;
}
and also:
sec.c
double x;
void p2()
{
x = 6;
}
After linking and compiling these two files, I'm printing x and get 0 as output.
Moreover, after printing y, I get 4018000 as output.
I understand that x overwrites y, but why do I get these values​​? What exactly does this mean?
First of all I'm pretty sure you using "%x" and not "%d in your printf. Second, I'm pretty sure it is 40180000 not 4018000 (an extra zero).
Assuming this is true, here's where you are getting this value:
In the first program, x and y are stored in the right next to each other in memory as ints (4 bytes). The second program links to the first program's "x" and treats it as a double (8 bytes), does not allocate new memory for the second program.
Now for the binary representation of "6" in IEEE double precision (link here)
0x01000000 00011000 00000000 00000000 00000000 00000000 00000000 00000000 is stored at "x"
HEX=0x4018000000000000
Since the first program sees only the int portion
0x01000000 00011000 00000000 00000000
=0x40180000
And since "%x" shows you the hex "40180000" is printed.
BTW: Reproduced your outcome just to make sure.

C - Using bit-shift operators for base conversion

I'm trying to convert some data from hex to base64 in C, I found an algorithm online but I would really like to know how it works rather than just implenting it and firing it off. If someone could please explain how the following is working I would appreciate it. I have been reading about the shift operators and I don't seem to understand them as much as I thought I did...it's not quite clicking for me.
for (x = 0; x < dataLength; x += 3)
{
/* these three 8-bit (ASCII) characters become one 24-bit number */
n = data[x] << 16;
if((x+1) < dataLength)
n += data[x+1] << 8;
if((x+2) < dataLength)
n += data[x+2];
/* this 24-bit number gets separated into four 6-bit numbers */
n0 = (uint8_t)(n >> 18) & 63;
n1 = (uint8_t)(n >> 12) & 63;
n2 = (uint8_t)(n >> 6) & 63;
n3 = (uint8_t)n & 63;
This code was taken from Wikibooks, it is NOT mine, I'm just trying to understand the bitshifting and how it's allowing me to convert the data.
Thank you for your help, I really appreciate it.
Source: Base64
First of all, the input data is not hex as you say. It's simply data stored as bytes. The code will give you the base64 representation of it (although the code you posted lacks the part which will map n0, n1, n2, n3 to printable ASCII characters).
Suppose the first three bytes of the input are (in binary representation, each letter represents a 0 or 1):
abcdefgh, ijklmnop, qrstuvwx
The first part of the code will combine them to a single 24-bit number. This is done by shifting the first one 16 bits to the left and the second one 8 bits to the left and adding:
abcdefgh0000000000000000 (abcdefgh << 16)
+ 00000000ijklmnop00000000 (ijklmnop << 8)
0000000000000000qrstuvwx
------------------------
abcdefghijklmnopqrstuvwx
Then it separates this into four 6-bit numbers by shifting and and'ing. For example, the second number is calculated by shifting 12 bits to the right and and'ing with 111111
n = abcdefghijklmnopqrstuvwx
n>>12 = 000000000000abcdefghijkl
63 = 000000000000000000111111
And'ing gives:
000000000000000000ghijkl
Ok here is a bit of explanation..
data[x] is an array of chars, a char is usuall 8bits.. (random 8bits number 01010101)
n is a 32bit number here is a random 32bit number(01011111000011110000111100001111)think there are 32bits there :)
remember n is 32bits and data is only 8bits.. lets go through the first line
n = data[x] << 16;
<<16 has precedence over the equal sign so its evaluated first.
data[x] << 16 means move the bits in memory that data[x] represents by 16bits to the left.
suppose data[x] = 'a' this is represented by 01100001 in memory(1 bytes), so lets move is 16bits to the left
n = 00000000 01100001 00000000 00000000
next we have
if((x+1) < dataLength)
n += data[x+1] << 8;
this says move the next char data[x+1] 8 bits and add it to n; so lets move it 8 bits first
( I assumed it was 'a' again)
00000000 00000000 01100001 00000000
(this is done in some register in your processor)
now lets add it to n
00000000 01100001 01100001 00000000
next part is
if((x+2) < dataLength)
n += data[x+2];
lets do the same thing here, notice there is no bit shifting, since the last 8bits of n are free!! all we need to do is add it to n
b = 01100010 (assumed data[x+2] = 'b')
adding it to n
00000000 01100001 01100001 01100010
great so now we have a 24bits number(actually n is 32bits but the last 24bits is what we need)
next part
n0 = (uint8_t)(n >> 18) & 63;
(take note n0 is only 8bits wide or a single unsigned byte)
take n and move it to the left by 18bits and "and" it with 63
n = 00000000 01100001 01100001 01100010
n moved 18bits to right is 00000000 00000000 00000000 00011000
now n is cast to an unsigned int of 8bits (uint8_t)
so now it becomes 00011000
last part is the & operator(bitwise and)
00011000 &
00111111
n0= 00011000
now repeat this for the rest

Wrong number produced when memcpy-ing data into an integer?

I have a char buffer like this
char *buff = "aaaa0006france";
I want to extract the bytes 4 to 7 and store it in an int.
int i;
memcpy(&i, buff+4, 4);
printf("%d ", i);
But it prints junk values.
What is wrong with this?
The string
0006
does not have the same binary representation as the integer 6. Instead, its bit representation is as four ASCII characters representing the glyph 0, the glyph 0, the glyph 0, then the glyph 6. This has hex representation
0x30303036
If you try blindly reinterpreting these bits as a number on a little-endian system, you get back 808,464,438. On a big-endian system, you'd get 909,127,728.
If you want to convert a substring of your string into a number, you will need to instead look for a function that converts a string of text into a number. You might want to try something like this:
char digits[5];
/* Copy over the digits in question. */
memcpy(digits, buff + 4, 4);
digits[4] = '\0'; /* Make sure it's null-terminated! */
/* Convert the string to a number. */
int i = strtol(digits + 4, NULL, 10);
This uses the strtol function, which converts a text string into a number, to explicitly convert the text to an integer.
Hope this helps!
Here you need to note down two things
How the characters are stored
Endianess of the system
Each characters (Alphabhets, numbers or special characters) are stored as 7 bit ASCII values. While doing memcpy of the string(array of characters) "0006" to a 4bytes int variable, we have to give address of string as source and address of int as destination like below.
char a[] = "0006";
int b = 0, c = 6;
memcpy(&b, a, 4);
Values of a and b are stored as below.
a 00110110 00110000 00110000 00110000
b 00000000 00000000 00000000 00000000
c 00000000 00000000 00000000 00000110
MSB LSB
Because ASCII value of 0 character is 48 and 6 character is 54. Now memcpy will try to copy whatever value present in the a to b. After memcpy value of b will be as below
a 00110110 00110000 00110000 00110000
b 00110110 00110000 00110000 00110000
c 00000000 00000000 00000000 00000110
MSB LSB
Next is endianess. Now consider we are keeping the value 0006 to the character buffer in some other way like a[0] = 0; a[1] = 0; a[2]=0; a[3] = 6; now if we do memcpy, we will the get the value as 100663296(0x6000000) not 6 if it is little endian machine. In big endian machine you will get the value as 6 only.
c 00000110 00000000 00000000 00000000
b 00000110 00000000 00000000 00000000
c 00000000 00000000 00000000 00000110
MSB LSB
So these two problems we need to consider while writing a function which converts number charters to integer value. Simple solution for these problem is to make use of existing system api atoi.
the below code might help you...
#include <stdio.h>
int main()
{
char *buff = "aaaa0006france";
char digits[5];
memcpy(digits, buff + 4, 4);
digits[4] = '\0';
int a = atoi(digits);
printf("int : %d", a);
return 0;
}

Binary representation of an unsigned long long

I am trying to get the binary form of an unsigned long long and store each bit of it in an array.
I have an input file like this:
0000000000000000 0000000000000000
FFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFF
3000000000000000 1000000000000001
where each entry is a 64-bit integer represented in hex. I am using an unsigned long long to hold this value then iterating over the bits and attempting to store them in an array, but some of the arrays have bits in the wrong position.
Here is what I have:
char key_in[17];
char plaintext_in[17];
//64-bit long variables to hold the 64-bit hex values in the input file
unsigned long long key, plaintext;
//I read an entry from the file with fscanf
fscanf(infile,"%s %s",&key_in, &plaintext_in)
//convert the numbers from hex to unsigned long long with strtoull
key = strtoull(key_in, NULL, 16);
plaintext = strtoull(plaintext_in, NULL, 16);
//initialize arrays with 64 positions that will hold the
//binary representation of the key and plaintext
int key_arr[64];
int pt_arr[64];
//fill the arrays with the binary representations
//of the plaintext and the key
int64_to_bin_array(key, key_arr, 64);
int64_to_bin_array(plaintext, pt_arr, 64);
//print both arrays
printArray(key_arr, 64);
printArray(pt_arr, 64);
here are the functions I created int64_to_bin_array and printArray:
/* Converts from an unsigned long long into an array of
integers that form the binary representation of a */
void int64_to_bin_array(unsigned long long a, int *b, int length)
{
int i;
for(i = 0; i < length; i++)
{
*(b+i) = (a >> i) & 1; //store the ith bit in b[i]
}
}
/* prints a one-dimensional array given
a pointer to it, and its length */
void printArray(int *arr, int length)
{
int i;
for(i = 0; i < length; i++)
{
printf("%d ", *(arr + i));
}
printf("\n\n");
}
When I print the array for the third input however, I receive an incorrect result:
input (in hex):
1. 3000000000000000 2. 1000000000000001
output (in binary):
1 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00001100
2 10000000 00000000 00000000 00000000 00000000 00000000 00000000 00001000
Can anyone see where I have made a mistake?
EDIT
I get the correct output after both reading and printing in reverse, but my problem is I need the array to have its most significant byte first so I can manipulate it. Any ideas how that can be done? Would I have to reassign it to a new array and copy the elements in reverse?
Try reading it the other way around. Let's take the last octet:
00001100 = 0x0C
00110000 = 0x30 <---
That corresponds yo your first first octet, 0x30.
For the second number:
00001000 = 0x08
00010000 = 0x10 <---
That corresponds to your first first octet, 0x10.
You'll probably get what you expect if you print it like this:
for(i = length - 1; i >= 0; i--)

Resources