Last active
September 21, 2021 11:24
-
-
Save wilhg/ce5cc170bc31a3a1fbc084a576d3e6eb to your computer and use it in GitHub Desktop.
Go - Shorten int64 as a String
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
import ( | |
"encoding/base64" | |
"encoding/binary" | |
"strings" | |
) | |
package util | |
import ( | |
"encoding/base64" | |
"encoding/binary" | |
"strings" | |
) | |
func ShortenInt64(i int64) string { | |
b := make([]byte, 8) | |
binary.BigEndian.PutUint64(b, uint64(i)) | |
result := base64.RawURLEncoding.EncodeToString(b) | |
return strings.TrimLeftFunc(result, func(r rune) bool { return r == 'A' }) | |
} | |
func DeshortenInt64(s string) (int64, error) { | |
leftPad := strings.Repeat("A", 11-len(s)) | |
bytes, err := base64.RawURLEncoding.DecodeString(leftPad + s) | |
if err != nil { | |
return 0, err | |
} | |
return int64(binary.BigEndian.Uint64(bytes)), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment