S
S
sddvxd2018-11-29 22:08:16
C++ / C#
sddvxd, 2018-11-29 22:08:16

Why is there a shift to the left (hash)?

Hello! Below is a construction for building a hash from a string, it is not clear to me why a shift is needed:

int hash = 0;
    char* string = "abc";
    const char* pchar = string;
    while(*pchar){
        hash <<= 1;
        hash ^= *pchar++;
    }

There are guesses that if it were not for the shift, the hash would not be unique:
//Without the shift
abc = 97, 98, 99
hash = 0 XOR 97 = 97
hash = 97 XOR 98 = 3
hash = 3 XOR 99 = 96
//Co shifted
hash = 0 XOR 97 = 97
hash << 1 = 194
hash = 194 XOR 98 = 160
hash << 1 = 320
hash = 320 XOR 99 = 291
shifted the number got bigger and it no longer occurs if I enter another string than with the case without shift. maybe that's why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2018-11-29
@sddvxd

If you xor the spell and the spell, the spell will come out.
If 256 unique hash values ​​are enough for you, that's fine.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question