go 代码练习


go 代码练习

1.1 把一个int32的数换算成二进制

//作业1,把一个int32的数换算成二进制
package main

import (
	"fmt"
	"math"
	"strings"
)

func main() {
	fmt.Println(BinaryFormat(0))
	fmt.Println(BinaryFormat(-1))
	fmt.Println(BinaryFormat(1))
	fmt.Println(BinaryFormat(260))
	fmt.Println(BinaryFormat(-260))
}

//输出一个int32对应的二进制表示
func BinaryFormat(n int32) string {
	a := uint32(n)               //将int32类型的数值转换成无符号的uint32类型
	sb := strings.Builder{}      //拼接字符串的函数
	c := uint32(math.Pow(2, 31)) //二进制为:10000000 00000000 00000000 00000000
	for i := 0; i < 32; i++ {
		if a&c > 0 {
			sb.WriteString("1")
		} else {
			sb.WriteString("0")
		}
		c >>= 1 //每次右偏移量1和n的二进制进行比对
		//fmt.Printf("当前二进制是%b<<<<<<<<<<\n",c)
	}
	//fmt.Printf("%d的二进制是%b,%d的十进制是%d\n", n, a, n, n)
	//fmt.Printf("2的31次方的二进制是%b,十进制是%d\n", c, c)

	return sb.String()
}

2.1 把字符串1998-10-01 08:10:00解析成time.Time,再格式化成字符串199810010810

//1. 把字符串1998-10-01 08:10:00解析成time.Time,再格式化成字符串199810010810
func timeshow() {
	format1 := "2006-05-16 09:53:03" //第一种时间格式模板
	format2 := "20060116095303" //第一种时间格式模板

	dt := "1998-10-01 08:10:00"
	loc,_ := time.LoadLocation("Asia/Shanghai")
	t,_ := time.ParseInLocation(format1, dt,loc) //解析成time.Time根据时区
	t1 := t.Format(format2)	//格式化时间
	fmt.Println(t1)
}
func main() {
	timeshow()
}

3.1 我们是每周六上课,输出我们未来4次课的上课日期(不考虑法定假日)

//1.我们是每周六上课,输出我们未来4次课的上课日期(不考虑法定假日)
func workday() {
	now := time.Now()
	days := int(time.Saturday - now.Weekday())
	fmt.Println(days)
	if days == 0 {
		days = 7
	}
	workday1 := now.Add(24 * time.Hour * time.Duration(days))  //time.Hour的类型是Duration,所以需要把days也转换成这种类型
	fmt.Println(workday1)
	for i := 1;i < 3;i ++ {
		workday1 = workday1.Add(24 * time.Hour * 7)  //time.Hour的类型是Duration,所以需要把days也转换成这种类型
		fmt.Println(workday1)
	}
}
func main() {
	workday()
}
Go