GO string转int int转string string转[]byte等

1.数值字母、字符串转整型值

strconv.Atoi("3")

2.整型值转字符

strconv.Itoa(3)

3.字符串转字节码

bytes := []byte("12345678")

4.字节码转字符串

str := fmt.Sprintf("%x", bytes)
str := string(bytes)
import "encoding/hex"
str := hex.EncodeToString(bytes)
 

5.int64与字节码

func Int64ToBytes(value int64) []byte {
	var bytes = make([]byte, 8)
	binary.BigEndian.PutUint64(bytes, uint64(value))
	return bytes
}

func BytesToInt64(bytes []byte) uint64 {
	return int64(binary.BigEndian.Uint64(bytes))
}

func BytesNtohll(b []byte) uint64 {
	return uint64(b[0])<<56 | uint64(b[1])<<48 |
		uint64(b[2])<<40 | uint64(b[3])<<32 |
		uint64(b[4])<<24 | uint64(b[5])<<16 |
		uint64(b[6])<<8 | uint64(b[7])
}

6.int与字节码

func InttoBytes(value uint32) []byte {
	bytes := make([]byte, 4)

	bytes[0] = uint8(value >> 24)
	bytes[1] = uint8(value >> 16)
	bytes[2] = uint8(value >> 8)
	bytes[3] = uint8(value)

	return []byte(bytes)
}

func BytesNtohl(b []byte) uint32 {
	return uint32(b[0])<<24 | uint32(b[1])<<16 |
		uint32(b[2])<<8 | uint32(b[3])
}

func BytesHtohl(b []byte) uint32 {
	return uint32(b[3])<<24 | uint32(b[2])<<16 |
		uint32(b[1])<<8 | uint32(b[0])
}

7.字符串IP转整形(字节码)

func InetAton(ip string) uint32 {

	buffer := strings.Split(ip, ".")
	first, _ := strconv.Atoi(buffer[0])
	second, _ := strconv.Atoi(buffer[1])
	third, _ := strconv.Atoi(buffer[2])
	fourth, _ := strconv.Atoi(buffer[3])

	var int_ip uint32
	int_ip += uint32(first << 24)
	int_ip += uint32(second << 16)
	int_ip += uint32(third << 8)
	int_ip += uint32(fourth)

	return int_ip
}

func IPv4Ntoa(ip uint32) string {
	return fmt.Sprintf("%d.%d.%d.%d",
		byte(ip>>24), byte(ip>>16),
		byte(ip>>8), byte(ip))
}

8.int32转string

// string 转 int32
num, err := strconv.ParseInt(`123456`, 10, 32)
if err != nil {
    panic(err)
}

// int32 转 string
str := strconv.FormatInt(123456, 10)
println(str)

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值