Created
November 11, 2023 17:20
-
-
Save brenoferreira/095bd392284e030a11df710655fcb4ed to your computer and use it in GitHub Desktop.
encode/decode two ints in binary
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 "fmt" | |
func encodeBitmap(num1, num2 int) (int, error) { | |
if !(0 <= num1 && num1 <= 10) || !(0 <= num2 && num2 <= 10) { | |
return 0, fmt.Errorf("Input integers must be between 0 and 10") | |
} | |
// Using bitwise left shift to create a bitmap | |
encodedValue := (num1 << 4) | num2 | |
return encodedValue, nil | |
} | |
func decodeBitmap(encodedValue int) (int, int) { | |
// Extracting the original values using bitwise AND and right shift | |
num2 := encodedValue & 0b1111 | |
num1 := (encodedValue >> 4) & 0b1111 | |
return num1, num2 | |
} | |
func main() { | |
// Example usage | |
num1 := 0 | |
num2 := 10 | |
encoded, err := encodeBitmap(num1, num2) | |
if err != nil { | |
fmt.Println("Error:", err) | |
return | |
} | |
decoded1, decoded2 := decodeBitmap(encoded) | |
fmt.Printf("Original Numbers: num1=%d, num2=%d\n", num1, num2) | |
fmt.Printf("Encoded Value: %b\n", encoded) | |
fmt.Printf("Decoded Numbers: num1=%d, num2=%d\n", decoded1, decoded2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment