How to generate a positive int64 from byte slice

93 views
Skip to first unread message

JohnGB

unread,
Sep 23, 2016, 8:25:42 PM9/23/16
to golang-nuts
I have a byte slice 32 bytes long, and I would like to use it to generate a positive int64.  Is there a standard way to do this, or do I need to write my own function (most likely using bit shifts)?

The backstory is that I need to generate unique (low collision likelihood) integer IDs from email addresses.  However it needs to be that every time a given email is used to generate an int64, that it generates the same int64.  I've settled on using a SHA3 hash with a salt to get a low collision byte slice, which I then need to generate a positive int64 from.

Caleb Spare

unread,
Sep 23, 2016, 8:32:24 PM9/23/16
to JohnGB, golang-nuts
You'll probably want to use encoding/binary.

But which 8 of the 32 bytes are you going to use? (or really, which 63 bits?)

-Caleb
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

JohnGB

unread,
Sep 24, 2016, 4:49:30 PM9/24/16
to golang-nuts, jgbe...@gmail.com
The 32 bytes were just a product of the hash function that we were using, but I've simplified it by changing the hash function to one that only generates 8 bytes.

My current solution is:

func EmailToID(email, salt string) int64 {

d := sha3.NewShake256()
d.Write([]byte(email))
d.Write([]byte(salt))
h := make([]byte, 8)
d.Read(h)

var n int64
buff := bytes.NewBuffer(h)
binary.Read(buff, binary.LittleEndian, &n)
if n < 0 {
n *= -1
}
return n
}

So, I'm actually using all 64 bits, but taking the absolute value of the resulting int64, which in effect means that I'm only considering 63 bytes.
Reply all
Reply to author
Forward
0 new messages