Created
June 22, 2022 17:36
-
-
Save xeoncross/3e0df2dd9ad6f7faf7d9ad38b8e05e46 to your computer and use it in GitHub Desktop.
Examples of bit lengths of different integer values: https://go.dev/play/p/gLZKA9B233I
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/binary" | |
"fmt" | |
) | |
func main() { | |
// subtract 1 from each answer since we're counting zero also | |
fmt.Printf("%d bits = %8b = %d\n", 2, byte(1<<2-1), 1<<2) | |
fmt.Printf("%d bits = %8b = %d\n", 3, byte(1<<3-1), 1<<3) | |
fmt.Printf("%d bits = %8b = %d\n", 4, byte(1<<4-1), 1<<4) | |
fmt.Printf("%d bits = %8b = %d\n", 5, byte(1<<5-1), 1<<5) | |
fmt.Printf("%d bits = %8b = %d\n", 6, byte(1<<6-1), 1<<6) | |
fmt.Printf("%d bits = %8b = %d\n", 7, byte(1<<7-1), 1<<7) | |
// Multiple bytes | |
fmt.Printf("%d\n", 1<<32-1) | |
fmt.Println("signed") | |
// Max values (signed) | |
fmt.Printf("%20d %08b\n", 1<<7-1, encodeToBytes(1<<7-1)) | |
fmt.Printf("%20d %08b\n", 1<<15-1, encodeToBytes(1<<15-1)) | |
fmt.Printf("%20d %08b\n", 1<<31-1, encodeToBytes(1<<31-1)) | |
fmt.Printf("%20d %08b\n", 1<<39-1, encodeToBytes(1<<39-1)) | |
fmt.Printf("%20d %08b\n", 1<<47-1, encodeToBytes(1<<47-1)) | |
fmt.Printf("%20d %08b\n", 1<<55-1, encodeToBytes(1<<55-1)) | |
fmt.Printf("%20d %08b\n", 1<<63-1, encodeToBytes(1<<63-1)) | |
fmt.Println("unsigned") | |
// Max values (unsigned) | |
fmt.Printf("%20d %08b\n", 1<<8-1, encodeToBytes(1<<8-1)) | |
fmt.Printf("%20d %08b\n", 1<<16-1, encodeToBytes(1<<16-1)) | |
fmt.Printf("%20d %08b\n", 1<<32-1, encodeToBytes(1<<32-1)) | |
fmt.Printf("%20d %08b\n", 1<<40-1, encodeToBytes(1<<40-1)) | |
fmt.Printf("%20d %08b\n", 1<<48-1, encodeToBytes(1<<48-1)) | |
fmt.Printf("%20d %08b\n", 1<<56-1, encodeToBytes(1<<56-1)) | |
fmt.Printf("%20d %08b\n", uint64(1<<64-1), encodeToBytes(1<<64-1)) | |
} | |
func encodeToBytes(v uint64) []byte { | |
buf := make([]byte, 8) | |
binary.BigEndian.PutUint64(buf, v) | |
return buf | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment