gobit-representation

Why is the length of a 32 byte hash 267 bits in binary and not 256 bits?


Given you hash some string to produce a 256bit output, why is the binary representation not of length 256

package main

import (
    "fmt"
    "crypto/sha256"
)

func main() {
    s := "1"
    m := sha256.Sum256([]byte(s))
    fmt.Println(len(m))
    b := fmt.Sprintf("%b\n", m[:])

    fmt.Println(len(b))
}

Output:

32 

267

Solution

  • If you'd print it, you'd see it immediately:

    fmt.Println(b)
    

    Which outputs:

    [1101011 10000110 10110010 1110011 11111111 110100 11111100 11100001 10011101 1101011 10000000 1001110 11111111 1011010 111111 1010111 1000111 10101101 10100100 11101010 10100010 101111 11101 1001001 11000000 11110 1010010 11011101 10110111 10000111 1011011 1001011]
    

    You're printing an array, and the fmt package adds square brackets [] and spaces between the binary representations of the individual bytes. Plus you also add a newline character to it in the format string.

    To get only the bits, you may use a loop like this:

    buf := &strings.Builder{}
    for _, v := range m {
        fmt.Fprintf(buf, "%08b", v)
    }
    b2 := buf.String()
    fmt.Println(b2)
    fmt.Println(len(b2))
    

    Note the %08b format string specifies the width to be 8 and use 0 as padding (if the byte value would be less than 8 bits).

    Which outputs:

    0110101110000110101100100111001111111111001101001111110011100001100111010110101110000000010011101111111101011010001111110101011101000111101011011010010011101010101000100010111100011101010010011100000000011110010100101101110110110111100001110101101101001011
    256
    

    Try these on the Go Playground.