Converting byte array into Integer

2,842 views
Skip to first unread message

Abhinav Srivastava

unread,
Oct 29, 2013, 3:51:44 AM10/29/13
to golan...@googlegroups.com
Hi,

I wrote a hasher file for sha1 hashing for chord protocol implementation. Here is the code :

package main

import (
    "fmt"
    "crypto/sha1"
    "time"
)

func main() {

    s:="Go is GOOD"
    h:=sha1.New()
    h.Write([]byte(s))
    bs:=h.Sum(nil)
    fmt.Println(s)
    fmt.Println("%x \n",bs)

    time.Sleep(12 * 1e9)
}


The problem is I want to convert the byte array obtained into Integer so that I can take mod of that value with some value. How to convert byte array to Integer in golang , I tried on net but could not find a good solution for this.

Also, please guide me if Golang is a good language for implementing distributed algorithm since I took up and have started learning golang for course project. Is there any limitation while implementing distributed algorithms like chord protocol.

Thansk & Regards

Abhinav

Jan Mercl

unread,
Oct 29, 2013, 3:59:14 AM10/29/13
to Abhinav Srivastava, golang-nuts
On Tue, Oct 29, 2013 at 8:51 AM, Abhinav Srivastava
<abhi1988s...@gmail.com> wrote:

If a byte array has to be interpreted as an integer then it's
effectively just a number (sequence of digits) in base 256 (every byte
is a single digit in that base). Apply standard rules for conversion
between number bases.

-j

Volker Dobler

unread,
Oct 29, 2013, 4:34:55 AM10/29/13
to golan...@googlegroups.com
Depending on the modulus all you need is the last byte of the sha1.
E.g. computing "sha1(s) % 4" would be just:
  bs[len(bs)-1] % 4

V.

Péter Szilágyi

unread,
Oct 29, 2013, 4:36:11 AM10/29/13
to Abhinav Srivastava, golang-nuts
Hi,

The simplest solution is:

new(big.Int).SetBytes(raw)

And btw, Go is perfect for distributed systems :) Take a peek at my messaging system, it's based on Pastry + Scribe at the core [1]. Specifically, for the ID space handling look at this source [2].

Cheers,
  Peter


--
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/groups/opt_out.

li...@eng.ucsd.edu

unread,
Apr 27, 2015, 9:12:29 PM4/27/15
to golan...@googlegroups.com, abhi1988s...@gmail.com
This is a nice one.
I tried func Uvarint(buf []byte) (uint64, int), did not work. 
Still need to convert [16]byte to []byte, but good enough.
Reply all
Reply to author
Forward
0 new messages