首页 > 其他 > 详细

3.6 二进制,十进制,十六进制转换

时间:2018-03-22 00:59:53      阅读:267      评论:0      收藏:0      [点我收藏+]

package main

import (
    "fmt"
    "strconv"
)

const bin = "10111"
const hex = "1A"
const oct = "12"
const dec = "10"
const floatNum = 16.123557

func main() {

    // Converts binary value into hex
    v, _ := ConvertInt(bin, 2, 16)
    fmt.Printf("Binary value %s converted to hex: %s\n", bin, v)

    // Converts hex value into dec
    v, _ = ConvertInt(hex, 16, 10)
    fmt.Printf("Hex value %s converted to dec: %s\n", hex, v)

    // Converts oct value into hex
    v, _ = ConvertInt(oct, 8, 16)
    fmt.Printf("Oct value %s converted to hex: %s\n", oct, v)

    // Converts dec value into oct
    v, _ = ConvertInt(dec, 10, 8)
    fmt.Printf("Dec value %s converted to oct: %s\n", dec, v)

    //... analogically any other conversion
    // could be done.

}

// ConvertInt converts the given string value of base
// to defined toBase.
func ConvertInt(val string, base, toBase int) (string, error) {
    i, err := strconv.ParseInt(val, base, 64)
    if err != nil {
        return "", err
    }
    return strconv.FormatInt(i, toBase), nil
}

/*
Binary value 10111 converted to hex: 17
Hex value 1A converted to dec: 26
Oct value 12 converted to hex: a
Dec value 10 converted to oct: 12

*/

3.6 二进制,十进制,十六进制转换

原文:https://www.cnblogs.com/zrdpy/p/8620779.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!