【问题标题】:Bitmasking conversion of CPU ids with Go使用 Go 对 CPU id 进行位掩码转换
【发布时间】:2017-03-07 05:41:14
【问题描述】:

我有一个掩码,其中包含 cpu_ids 的二进制计数(0xA00000800000 用于 3 个 CPU),我想将其转换为逗号分隔的 cpu_ids 的string"0,2,24"

我做了以下 Go 实现(我是 Go 初学者)。这是最好的方法吗?尤其是字节缓冲区的处理似乎效率低下!

package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main(){
    cpuMap     := "0xA00000800000"
    cpuIds     = getCpuIds(cpuMap)
    fmt.Println(cpuIds)
}

func getCpuIds(cpuMap string) string {
    // getting the cpu ids
    cpu_ids_i, _ := strconv.ParseInt(cpuMap, 0, 64) // int from string
    cpu_ids_b := strconv.FormatInt(cpu_ids_i, 2)    // binary as string

    var buff bytes.Buffer
    for i, runeValue := range cpu_ids_b {
        // take care! go returns code points and not the string    
        if runeValue == '1' {
            //fmt.Println(bitString, i)
            buff.WriteString(fmt.Sprintf("%d", i))
        }
        if (i+1 < len(cpu_ids_b)) && (runeValue == '1') {
            //fmt.Println(bitString)
            buff.WriteString(string(","))
        }

    }
    cpuIds := buff.String()
    // remove last comma
    cpuIds = cpuIds[:len(cpuIds)-1]
    //fmt.Println(cpuIds)
    return cpuIds
}

返回:

“0,2,24”

【问题讨论】:

  • 您可以将导入添加到示例中吗?尝试使用go doc 时有很大帮助:)

标签: string go binary binary-operators


【解决方案1】:

您所做的实际上是从左到右以二进制表示形式输出 "1" 的索引,并从左侧开始索引计数(不寻常)。

您可以使用位掩码和位运算符来实现相同的目的,而无需将其转换为二进制字符串。我会返回一片索引而不是它的格式化字符串,更容易使用。

要测试最低(最右边)位是否为1,您可以像x&amp;0x01 == 1 一样执行此操作,并将整数按位向右移动:x &gt;&gt;= 1。移位后,最右边的位“消失”,之前的第 2 位变为第 1 位,因此您可以使用相同的逻辑再次测试。您可以循环直到数字大于 0(这意味着它有 1 位)。

有关按位运算的更多示例,请参阅此问题:Difference between some operators "|", "^", "&", "&^". Golang

当然,如果我们测试最右边的位并右移,我们会以 reverse 顺序获得位(索引)(与您想要的相比),并且索引从右开始计数,所以我们必须在返回结果之前更正此问题。

所以解决方案是这样的:

func getCpuIds(cpuMap string) (r []int) {
    ci, err := strconv.ParseInt(cpuMap, 0, 64)
    if err != nil {
        panic(err)
    }

    count := 0
    for ; ci > 0; count, ci = count+1, ci>>1 {
        if ci&0x01 == 1 {
            r = append(r, count)
        }
    }

    // Indices are from the right, correct it:
    for i, v := range r {
        r[i] = count - v - 1
    }
    // Result is in reverse order:
    for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
        r[i], r[j] = r[j], r[i]
    }

    return
}

输出(在Go Playground上试试):

[0 2 24]

如果由于某种原因您需要以逗号分隔 string 的结果,您可以通过以下方式获得:

buf := &bytes.Buffer{}
for i, v := range cpuIds {
    if i > 0 {
        buf.WriteString(",")
    }
    buf.WriteString(strconv.Itoa(v))
}
cpuIdsStr := buf.String()
fmt.Println(cpuIdsStr)

输出(在Go Playground上试试):

0,2,24

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多