arrays - 按位移位以及此解决方案为何有效

标签 arrays go bit-manipulation bit shift

我一直在 codefights.com 上进行代码战斗,我在下面遇到了这个问题。我已经自己解决了这个问题,但是当我研究其他人的解决方案时,我发现一个比我的短得多的解决方案,但我似乎无法理解他们为什么这样做。

问题是:

You are given an array of up to four non-negative integers, each less than 256. Your task is to pack these integers into one number M in the following way:

The first element of the array occupies the first 8 bits of M; The second element occupies next 8 bits, and so on. Return the obtained integer M.

Note: the phrase "first bits of M" refers to the least significant bits of M - the right-most bits of an integer. For further clarification see the following example.

Example

For a = [24, 85, 0], the output should be arrayPacking(a) = 21784.

An array [24, 85, 0] looks like [00011000, 01010101, 00000000] in binary. After packing these into one number we get 00000000 01010101 00011000 (spaces are placed for convenience), which equals to 21784.

他们的回答是:

func arrayPacking(a []int) (sum int) {
    for i := range a {
        sum += a[len(a) - i - 1] << uint((len(a) - i - 1) * 8)
    }
    return
}

这段代码如何仅通过使用 0、8、16 等间隔返回正确的偏移量?我最近一直在按位研究很多,但我似乎仍然无法理解为什么它有效。

最佳答案

首先,用 Go 编写解决方案。我们将 little-endian、base-256 数字转换为 base-2(二进制)数字。左移 8 位乘以 256。

package main

import (
    "fmt"
)

func pack(digits []int) (number int) {
    // digits are little-endian, base-256 (1 << 8 = 256)
    for i, digit := range digits {
        number += digit << uint(i*8)
    }
    return number
}

func main() {
    a := []int{24, 85, 0}
    m := pack(a)
    fmt.Println(m)
}

Playground :https://play.golang.org/p/oo_n7CiAHwG

输出:

21784

现在你应该能猜出他们丑陋的答案了:

func arrayPacking(a []int) (sum int) {
    for i := range a {
        sum += a[len(a) - i - 1] << uint((len(a) - i - 1) * 8)
    }
    return
}

关于arrays - 按位移位以及此解决方案为何有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407199/

相关文章:

algorithm - 用很少的给定信息导出特定的比特流

.net - .Net中具有Count属性的最小接口(interface)是什么

go - 存储所有符合相同接口(interface)的类型的构造函数集合

arrays - 相对排序两个数组的最小交换

syntax - 如何将自定义结构放入堆栈然后能够访问所有字段?

xml - 解码 XML 注释

python - 根据给定的位信息提取 Numpy 数组的索引

c - 如何按位异或两个 C char 数组?

javascript - 如何使用 tsv 或 csv 从 txt 文件中获取数据以排列在 d3.js 中?

javascript - 将 jQuery inArray 与 JavaScript 对象数组结合使用