如何使用Scala扩展二进制文件?

时间:2019-03-04 15:21:40

标签: scala binary parity

我正在尝试完成以下练习:

My exercise

我在下面尝试过,但是我的代码未按预期运行。

def extend(p: Long): Long = {

  var e =  p.toBinaryString

  if ( e.count(_== '1') % 2 == 0) {
    e="0"+e
  }else {
    e="1"+e
  }

  e.toLong
} 

我在这里做错了什么?我不明白如何更改二进制十六进制格式。

@Test def testExtend() {
  assertEquals("extend(0x0000000000000000L)", 0x0000000000000000L, extend(0x0000000000000000L))
  assertEquals("extend(0x0000000000000001L)", 0x8000000000000001L, extend(0x0000000000000001L))
  assertEquals("extend(0x0000000000000011L)", 0x0000000000000011L, extend(0x0000000000000011L))
  assertEquals("extend(0x8000000000000000L)", 0x0000000000000000L, extend(0x8000000000000000L))
  assertEquals("extend(0x8000000000F00000L)", 0x0000000000F00000L, extend(0x8000000000F00000L))
  assertEquals("extend(0x0000001000300000L)", 0x8000001000300000L, extend(0x0000001000300000L))
}

1 个答案:

答案 0 :(得分:1)

第一个问题是.toLong假设要转换的是十进制值的String表示形式。因此,假设"10"代表十个(十进制),而不是两个(二进制)。

下一个问题是Long的长度是固定的。您不能添加额外的内容。您必须翻转现有位。

def extend(p: Long): Long =
  if (p.toBinaryString.count(_ == '1') % 2 == 0) p
  else p ^ Long.MinValue

测试:

0x0000000000000000L == extend(0x0000000000000000L)  //res0: Boolean = true
0x8000000000000001L == extend(0x0000000000000001L)  //res1: Boolean = true
0x0000000000000011L == extend(0x0000000000000011L)  //res2: Boolean = true
0x0000000000000000L == extend(0x8000000000000000L)  //res3: Boolean = true
0x0000000000F00000L == extend(0x8000000000F00000L)  //res4: Boolean = true
0x8000001000300000L == extend(0x0000001000300000L)  //res5: Boolean = true