On 22 July 2015 at 23:01, Victor Hooi <
victo...@gmail.com> wrote:
> Aha, ok, so that explains it - I should convert the array to a slice before
> passing it to binary.Read, which is what bytes.NewBuffer() does.
>
>> input_string := "The quick brown fox jumped over the lazy dog"
>> var myint int
>> hashBytes := sha1.Sum([]byte(input_string))
>> buf := bytes.NewBuffer(hashBytes[:])
>> binary.Read(buf, binary.LittleEndian, &myint)
>> fmt.Println(hashBytes)
>> fmt.Println(myint)
>
>
> However, for some odd reason, I'm now getting 0 (zero) as the value of
> myint?
+1 to rob's remarks. But I'll just say that the above code can
be quite a lot simpler:
hashBytes := sha1.Sum([]byte("The quick brown fox jumped over the
lazy dog"))
myint := binary.BigEndian.Uint64(hashBytes[:])
http://play.golang.org/p/jK_v5Y_0tX
BTW note that you can't use binary.Read with int because
it can vary in size (that's why your code doesn't work).
If you changed int to (say) int64, it could work.
cheers,
rog.
>
> On Thursday, 23 July 2015 07:48:16 UTC+10,
aro...@gmail.com wrote:
>>
>> sha1.Sum returns an array ([20]byte), not a slice, but bytes.NewBuffer
>> takes a slice, not an array.
>>
>> hashBytes := sha1.Sum([]byte(s))
>> buf := bytes.NewBuffer(hashBytes[:])
>>
>> should work.
>>
>> On Wednesday, July 22, 2015 at 2:37:10 PM UTC-7, Victor Hooi wrote:
>>>
>>> I'm trying to convert a sha1 hash into an integer, so that it can use it
>>> to index an array of words (i.e. to pick a word from the list). s below is a
>>> string:
>>>
>>> var myint int
>>> buf := bytes.NewBuffer(sha1.Sum([]byte(s)))
>>> binary.Read(buf, binary.LittleEndian, &myint)
>>>
>>> However, I get:
>>>
>>>> cannot use sha1.Sum(([]byte)(s)) (type [20]byte) as type []byte in
>>>> argument to bytes.NewBuffer
>>>
>>>
>>> Is it somehow not able to treat a 20-byte array as a []byte?
>>>
>>> Also, if there's an better way to do this, please let me know.
>