github.com/iDigitalFlame/xmt@v0.5.4/util/number.go (about) 1 // Copyright (C) 2020 - 2023 iDigitalFlame 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU General Public License as published by 5 // the Free Software Foundation, either version 3 of the License, or 6 // any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU General Public License for more details. 12 // 13 // You should have received a copy of the GNU General Public License 14 // along with this program. If not, see <https://www.gnu.org/licenses/>. 15 // 16 17 package util 18 19 // HexTable is a static string hex mapping constant string. This can be used 20 // multiple places to prevent reuse. 21 const HexTable = "0123456789ABCDEF" 22 23 // Itoa converts val to a decimal string. 24 // 25 // Similar to the "strconv" variant. 26 // Taken from the "internal/itoa" package. 27 func Itoa(v int64) string { 28 if v < 0 { 29 return "-" + Uitoa(uint64(-v)) 30 } 31 return Uitoa(uint64(v)) 32 } 33 34 // Uitoa converts val to a decimal string. 35 // 36 // Similar to the "strconv" variant. 37 // Taken from the "internal/itoa" package. 38 func Uitoa(v uint64) string { 39 if v == 0 { 40 return "0" 41 } 42 var ( 43 i = 0x13 44 b [20]byte 45 ) 46 for v >= 0xA { 47 n := v / 0xA 48 b[i] = byte(0x30 + v - n*0xA) 49 i-- 50 v = n 51 } 52 b[i] = byte(0x30 + v) 53 return string(b[i:]) 54 } 55 56 // Uitoa16 converts val to a hexadecimal string. 57 func Uitoa16(v uint64) string { 58 if v == 0 { 59 return "0" 60 } 61 var ( 62 i = 0x13 63 b [20]byte 64 ) 65 for { 66 n := (v >> (4 * uint(0x13-i))) 67 b[i] = HexTable[n&0xF] 68 if i--; n <= 0xF { 69 break 70 } 71 } 72 return string(b[i+1:]) 73 }