码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-03-22 01:41:07      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:parse   any   main   port   UNC   class   value   fun   markdown   


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 二进制,十进制,十六进制转换

标签:parse   any   main   port   UNC   class   value   fun   markdown   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!