我被分配了一项任务,我必须在 scala 中创建一个 SECEncoder,它将 32 位字编码为 40 位字,其中 40 位字的最低有效位是 32 位字。
即使最多有一位错误,SECDecoder 也应该能够返回相同的 32 位字。
到目前为止,我的编码器能够检查简单的奇偶校验位并将它们添加到字中,但是我被我的解码器困住了,因为我无法从中正确检索 32 位字。
val p = Vector(0x55555555L, 0x33333333L, 0x471C71C7L, 0x0F0F0F0FL, 0x41F07C1FL, 0x3F03F03FL, 0x701FC07FL, 0x00FF00FFL)
def ham(j: Int, m: Int) = ((0 to 31).map(i => (((m & p(j-1)) >> i)&1)).sum) % 2
def SECEncode(d: Int): Long = {
val ps = Vector(ham(1, d), ham(2, d), ham(3, d), ham(4, d), ham(5, d), ham(6, d), ham(7, d), ham(8, d))
// calculates the value of the parity bits
var dN = d.toLong
for (i <- 0 to 7) {
dN += (ps(i) << (31.toLong + i.toLong))
}
dN
}
def SECDecode(s: Long): Int = {
val d = (s & Int.MaxValue).toInt // takes the 32 least significant bits of _s_
val check = (s >>> 31) ^ (SECEncode(d) >>> 31) // checks which bits in the encoding differ
import scala.collection.mutable.Buffer
val buf1 = Buffer[Long]()
val buf2 = Buffer[Long]()
for (i <- 0 to 7) {
if (((check >>> i)&1) == 1) buf1 += p(i) else buf2 += p(i)
}
val b = buf1.reduce(_ ^ _) | buf2.reduce(_ | _)
(((b ^ Int.MaxValue)) ^ d).toInt
}
所以我本质上想要做的是通过类似于汉明的原理计算奇偶校验位(不幸的是我没有太多的知识),其中添加到 32 位字的位是奇偶校验位。
在解码器中,我检查给定字的奇偶校验位和编码给定字的奇偶校验位的差异,以便查看哪些奇偶校验位不同。
我卡住的地方是我如何准确计算哪个位与整个 32 位字不同,然后更改它?当我尝试这样做时,我得到了一些东西,但我从来没有得到确切的东西。
我是在完全错误的方向上前进还是我只是错过了什么?