...

Source file src/internal/itoa/itoa.go

Documentation: internal/itoa

     1  // Copyright 2021 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Simple conversions to avoid depending on strconv.
     6  
     7  package itoa
     8  
     9  // Itoa converts val to a decimal string.
    10  func Itoa(val int) string {
    11  	if val < 0 {
    12  		return "-" + Uitoa(uint(-val))
    13  	}
    14  	return Uitoa(uint(val))
    15  }
    16  
    17  // Uitoa converts val to a decimal string.
    18  func Uitoa(val uint) string {
    19  	if val == 0 { // avoid string allocation
    20  		return "0"
    21  	}
    22  	var buf [20]byte // big enough for 64bit value base 10
    23  	i := len(buf) - 1
    24  	for val >= 10 {
    25  		q := val / 10
    26  		buf[i] = byte('0' + val - q*10)
    27  		i--
    28  		val = q
    29  	}
    30  	// val < 10
    31  	buf[i] = byte('0' + val)
    32  	return string(buf[i:])
    33  }
    34  
    35  const hex = "0123456789abcdef"
    36  
    37  // Uitox converts val (a uint) to a hexadecimal string.
    38  func Uitox(val uint) string {
    39  	if val == 0 { // avoid string allocation
    40  		return "0x0"
    41  	}
    42  	var buf [20]byte // big enough for 64bit value base 16 + 0x
    43  	i := len(buf) - 1
    44  	for val >= 16 {
    45  		q := val / 16
    46  		buf[i] = hex[val%16]
    47  		i--
    48  		val = q
    49  	}
    50  	// val < 16
    51  	buf[i] = hex[val%16]
    52  	i--
    53  	buf[i] = 'x'
    54  	i--
    55  	buf[i] = '0'
    56  	return string(buf[i:])
    57  }
    58  

View as plain text