builtin: fix int to hex

pull/4203/head
penguindark 2020-04-02 17:16:17 +02:00 committed by GitHub
parent 8c050eff07
commit 83289d74a7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 117 additions and 4 deletions

View File

@ -235,8 +235,66 @@ pub fn (n int) hex1() string {
}
*/
pub fn (nn int) hex() string {
mut n := u32(nn)
pub fn (nn byte) hex() string {
if nn == 0 {
return '0'
}
mut n := nn
max := 2
mut buf := malloc(max + 1)
mut index := max
buf[index--] = `\0`
for n > 0 {
d := n & 0xF
n = n >> 4
buf[index--] = if d < 10 { d + `0` } else { d + 87 }
}
//buf[index--] = `x`
//buf[index] = `0`
index++
return tos(buf + index, (max - index))
}
pub fn (nn i8) hex() string {
return byte(nn).hex()
}
pub fn (nn u16) hex() string {
if nn == 0 {
return '0'
}
mut n := nn
max := 5
mut buf := malloc(max + 1)
mut index := max
buf[index--] = `\0`
for n > 0 {
d := n & 0xF
n = n >> 4
buf[index--] = if d < 10 { d + `0` } else { d + 87 }
}
//buf[index--] = `x`
//buf[index] = `0`
index++
return tos(buf + index, (max - index))
}
pub fn (nn i16) hex() string {
return u16(nn).hex()
}
pub fn (nn u32) hex() string {
if nn == 0 {
return '0'
}
mut n := nn
max := 10
mut buf := malloc(max + 1)
@ -254,7 +312,15 @@ pub fn (nn int) hex() string {
return tos(buf + index, (max - index))
}
pub fn (nn int) hex() string {
return u32(nn).hex()
}
pub fn (nn u64) hex() string {
if nn == 0 {
return '0'
}
mut n := nn
max := 18
mut buf := malloc(max + 1)
@ -276,8 +342,7 @@ pub fn (nn u64) hex() string {
}
pub fn (nn i64) hex() string {
mut n := u64(nn)
return n.hex()
return u64(nn).hex()
}
// ----- utilities functions -----

View File

@ -157,3 +157,51 @@ fn test_int_decl() {
assert typeof(x7) == 'u64'
}
fn test_int_to_hex() {
// array hex
st := [byte(`V`),`L`,`A`,`N`,`G`]
assert st.hex() == "564c414e47"
assert st.hex().len == 10
st1 := [byte(0x41)].repeat(100)
assert st1.hex() == "41".repeat(100)
//--- int to hex tests
c0 := 12
// 8Bit
assert byte(0).hex() == "0"
assert byte(c0).hex() == "c"
assert i8(c0).hex() == "c"
assert byte(127).hex() == "7f"
assert i8(127).hex() == "7f"
assert byte(255).hex() == "ff"
assert byte(-1).hex() == "ff"
// 16bit
assert u16(0).hex() == "0"
assert i16(c0).hex() == "c"
assert u16(c0).hex() == "c"
assert i16(32767).hex() == "7fff"
assert u16(32767).hex() == "7fff"
assert i16(-1).hex() == "ffff"
assert u16(65535).hex() == "ffff"
// 32bit
assert u32(0).hex() == "0"
assert c0.hex() == "c"
assert u32(c0).hex() == "c"
assert 2147483647.hex() == "7fffffff"
assert u32(2147483647).hex() == "7fffffff"
assert (-1).hex() == "ffffffff"
assert u32(4294967295).hex() == "ffffffff"
// 64 bit
assert u64(0).hex() == "0"
assert i64(c0).hex() == "c"
assert u64(c0).hex() == "c"
assert i64(9223372036854775807).hex() == "7fffffffffffffff"
assert u64(9223372036854775807).hex() == "7fffffffffffffff"
assert i64(-1).hex() == "ffffffffffffffff"
assert u64(18446744073709551615).hex() == "ffffffffffffffff"
}