Created
May 6, 2023 05:59
-
-
Save neepoo/aaf7a46cc9cb121bbbad4e5d735d5246 to your computer and use it in GitHub Desktop.
10进制转换成x(2-36)进制,created by jb
This file contains hidden or 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 radix | |
import ( | |
"strconv" | |
"testing" | |
) | |
func radix(x, base int) string { | |
var s string | |
if x == 0 { | |
return "0" | |
} | |
for x > 0 { | |
r := x % base | |
if r >= 10 { | |
s = string(rune(r-10+'A')) + s | |
} else { | |
s = strconv.Itoa(r) + s | |
} | |
x /= base | |
} | |
return s | |
} | |
func TestRadix(t *testing.T) { | |
cases := []struct { | |
x int | |
base int | |
want string | |
}{ | |
{15, 2, "1111"}, | |
{13, 8, "15"}, | |
{255, 16, "FF"}, | |
{1024, 2, "10000000000"}, | |
{0, 5, "0"}, | |
} | |
for _, c := range cases { | |
got := radix(c.x, c.base) | |
if got != c.want { | |
t.Errorf("radix(%d, %d) == %s, want %s", c.x, c.base, got, c.want) | |
} | |
} | |
} | |
func TestRadixBase2(t *testing.T) { | |
cases := []struct { | |
x int | |
base int | |
want string | |
}{ | |
{0, 2, "0"}, | |
{1, 2, "1"}, | |
{2, 2, "10"}, | |
{3, 2, "11"}, | |
{4, 2, "100"}, | |
{5, 2, "101"}, | |
{8, 2, "1000"}, | |
{10, 2, "1010"}, | |
{13, 2, "1101"}, | |
{15, 2, "1111"}, | |
{16, 2, "10000"}, | |
{31, 2, "11111"}, | |
{32, 2, "100000"}, | |
{63, 2, "111111"}, | |
{64, 2, "1000000"}, | |
{255, 2, "11111111"}, | |
{256, 2, "100000000"}, | |
{511, 2, "111111111"}, | |
{512, 2, "1000000000"}, | |
{1023, 2, "1111111111"}, | |
{1024, 2, "10000000000"}, | |
{100, 8, "144"}, | |
{255, 8, "377"}, | |
{512, 8, "1000"}, | |
{1000, 8, "1750"}, | |
{4095, 8, "7777"}, | |
{4096, 8, "10000"}, | |
{10000, 8, "23420"}, | |
{65535, 8, "177777"}, | |
{65536, 8, "200000"}, | |
{100, 16, "64"}, | |
{255, 16, "FF"}, | |
{256, 16, "100"}, | |
{1000, 16, "3E8"}, | |
{4095, 16, "FFF"}, | |
{4096, 16, "1000"}, | |
{10000, 16, "2710"}, | |
{65535, 16, "FFFF"}, | |
{65536, 16, "10000"}, | |
{100000, 16, "186A0"}, | |
{1000000, 16, "F4240"}, | |
{10000000, 16, "989680"}, | |
} | |
for _, c := range cases { | |
got := radix(c.x, c.base) | |
if got != c.want { | |
t.Errorf("radix(%d, %d) == %s, want %s", c.x, c.base, got, c.want) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment