首页 > 其他分享 >字符编码 XUTF

字符编码 XUTF

时间:2022-10-05 16:44:09浏览次数:45  
标签:编码 return 字符 unicodeHexVal XUTF unicodeVal unicodeBytesVal && decimalLen


/*
* Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved.
* Description: 上机编程认证
* Note: 缺省代码仅供参考,可自行决定使用、修改或删除
* 只能import Go标准库
*/

package main

import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)

func getDecimalByteLength(decimalLens int) int {
if decimalLens < 0 {
return -1
}
if decimalLens >= 0 && decimalLens < 8 {
return 1
}
if decimalLens >= 8 && decimalLens < 12 {
return 2
}
if decimalLens >= 12 && decimalLens < 17 {
return 3
}
if decimalLens >= 17 && decimalLens < 22 {
return 4
}
if decimalLens >= 22 && decimalLens < 27 {
return 5
}
if decimalLens >= 27 && decimalLens < 32 {
return 6
}
return -1
}

// 待实现函数,在此函数中填入答题代码
func utfEncoding(unicodeVal string) string {
// 转为 二进制判断个数
unicodeIntVal,_ := strconv.ParseInt(unicodeVal, 10, 64)
decimalVal := fmt.Sprintf("%b", unicodeIntVal)
decimalLens := len(decimalVal)
decimalByteLens := getDecimalByteLength(decimalLens)
unicodeBytesVal := ""
if decimalByteLens == 1 {
needLens := 8 - decimalByteLens
needZeroLens := needLens - decimalLens
unicodeBytesVal = "1"
for i:= 0; i < needZeroLens; i++ {
unicodeBytesVal += "0"
}
unicodeBytesVal += decimalVal
} else {
unicodeCount := 0
for i := 0; i < decimalByteLens; i++ {
unicodeBytesVal += "0"
}
unicodeBytesVal += "1"
needHeaderLens := 8 - decimalByteLens - 1
actualHeaderLens := decimalLens - (decimalByteLens-1)*6

needZeroLens := needHeaderLens - actualHeaderLens
for i:= 0; i < needZeroLens; i++ {
unicodeBytesVal += "0"
}
for i:= 0; i < actualHeaderLens; i++ {
unicodeBytesVal += string(decimalVal[i])
}
for i:= actualHeaderLens; i < decimalLens; i++ {
if unicodeCount % 6 == 0 {
unicodeBytesVal += "01"
unicodeCount = 0
}
unicodeBytesVal += string(decimalVal[i])
unicodeCount ++
}
}
//转为16进制
unicodeDecVal,_ := strconv.ParseInt(unicodeBytesVal, 2, 64)
unicodeHexVal := strconv.FormatInt(unicodeDecVal, 16)
// 判断奇偶
if len(unicodeHexVal) % 2 != 0 {
unicodeHexVal = "0" + unicodeHexVal
}
// 转大写
unicodeHexVal = strings.ToUpper(unicodeHexVal)
fmt.Println(unicodeHexVal)
return unicodeHexVal
}

func main() {
inputReader := bufio.NewReader(os.Stdin)
unicodeVal, err := inputReader.ReadString('\n')
if err != nil && err != io.EOF {
fmt.Println(err.Error())
return
}
unicodeVal = strings.TrimRight(unicodeVal, "\r\n")
unicodeVal = strings.TrimSpace(unicodeVal)
fmt.Println(utfEncoding(unicodeVal))
}

标签:编码,return,字符,unicodeHexVal,XUTF,unicodeVal,unicodeBytesVal,&&,decimalLen
From: https://www.cnblogs.com/gongxianjin/p/16755819.html

相关文章