Golang基础-类型转换

Numbers

int64取值范围是多少?(面试题)
[-2^63, 2^63-1]
int64就是用64bit表示一个数字,由于需要区分正负,所以减去1位的符号位,符号位0表示正,1表示负。剩下63位来表示数字。
或者这样想,不考虑符号,64bit最大的数是2^64-1,也就是64位全1。再把这个范围平分到0的左边和右边。

有个二进制表示数字的问题。
在计算机系统中,数值一律用补码来表示和存储。原因在于,使用补码,可以将符号位和数值域统一处理;同时,加法和减法也可以统一处理。
正数的原码、反码、补码完全一样。
0的反码、补码都为0。
负数以其绝对值的补码形式表达。需要先获得其绝对值的原码,再得反码,再得补码。

  • 原码:在数值前面增加了一位符号位(即最高位为符号位),正数该位为0,负数该位为1
  • 反码:负数的反码是在其原码的基础上, 符号位不变,其余各个位取反
  • 补码:反码加1称为补码。

-29的二进制表达(补码):

  • 绝对值:29
  • 原码:10011101
  • 反码:11100010
  • 补码:11100011

int8最大值为127,二进制为01111111。最小值-128,二进制为10000000。

  • -128的补码为:10000000
  • 反码为:01111111
  • 原码为:11111111

原码(Sign-Magnitude)、反码(ones' Complement)、补码(two's Complement)。英文资料里的提法跟我们不一样。
扩展:二进制的原码、反码、补码 - 知乎

二进制表示小数(定点,区别与浮点)
例如:178.625
整数部分用除2取余的方法,求得:10110010
小数部分用乘2取整的方法,求得:101
合起来即是:10110010.101

乘2取整的意思是:
0.625*2 = 1.25, 整数部分为1,所以二进制小数点后第一位为1(然后1.25把这个1减掉,只剩小数部分0.25,继续乘2取整)
0.25*2 = 0.5, 整数部分为0, 所以二进制小数点后第二位为0
0.5*2 = 1, 整数部分为1, 所以二进制小数点后第二位为1
合起来小数部分就是0.101
就是说,乘2的过程只考虑小数部分,整数部分是1还是0都按0算;取整的过程才考虑整数部分是1还是0,决定二进制表示对应位是多少。
可以看出来,0.625 = 1/2 * 1 + 1/4 * 0 + 1/8 * 1 = 0.5 + 0 + 0.125
跟整数表示很像,整数是2的n次方,这里是1/2的n次方。
面试题 05.02. 二进制数转字符串 - 力扣(Leetcode)

类型转换

Converting between types is done via a function with the name of the type to convert to.
Golang没有类型的自动转换,需要手动转换类型。也就是说不能拿float乘int

var x int = 42 // x has type int
f := float64(x) // f has type float64 (ie. 42.0)
var y float64 = 11.9 // y has type float64
i := int(y) // i has type int (ie. 11)

// this line produces an error
value := float32(2.0) * x // invalid operation: mismatched types float32 and int

// you must convert int type to float32 before performing arithmetic operation
value := float32(2.0) * float32(x)

字符串类型转换

import "strconv"

// string转int
var intString string = "42"
var i, err = strconv.Atoi(intString)

// int转string(数字加上引号)
var number int = 12
var s string = strconv.Itoa(number)

// 使用string转换相当于将ASCII编号转为相应字符
var num int = 65
str := string(num) // str is now "A" not "65"

strconv包的其他方法

Method Purpose
ParseBool Convert string to bool
FormatBool Convert bool to string
ParseFloat Convert string to float
FormatFloat Convert float to string
ParseInt Convert string to int
FormatInt Convert int to string

Exercise

package cars

// CalculateWorkingCarsPerHour calculates how many working cars are
// produced by the assembly line every hour.
func CalculateWorkingCarsPerHour(productionRate int, successRate float64) float64 {
	return float64(productionRate) * successRate / 100
}

// CalculateWorkingCarsPerMinute calculates how many working cars are
// produced by the assembly line every minute.
func CalculateWorkingCarsPerMinute(productionRate int, successRate float64) int {
	return int(CalculateWorkingCarsPerHour(productionRate, successRate))/60
}

// CalculateCost works out the cost of producing the given number of cars.
func CalculateCost(carsCount int) uint {
	return uint(carsCount / 10 * 95000 + (carsCount % 10) * 10000)
}
posted @ 2023-02-18 13:59  roadwide  阅读(178)  评论(0编辑  收藏  举报