-2

I am trying to complete the below exercise:

My exercise

I have attempted it below, but my code is not acting as expected.

def extend(p: Long): Long = {

  var e =  p.toBinaryString

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

  e.toLong
} 

What am I doing wrong here? I don't understand how I'm supposed to change binary right Hex.

@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))
}
James Whiteley
  • 3,363
  • 1
  • 19
  • 46
S.H
  • 33
  • 5
  • 1
    "not acting as expected" is not a precise enough error description for us to help you. *What* doesn't work? *How* doesn't it work? What trouble do you have with your code? Do you get an error message? What is the error message? Is the result you are getting not the result you are expecting? What result do you expect and why, what is the result you are getting and how do the two differ? Is the behavior you are observing not the desired behavior? What is the desired behavior and why, what is the observed behavior, and in what way do they differ? – Jörg W Mittag Mar 05 '19 at 08:31

1 Answers1

1

The first problem is that .toLong assumes that what's being converted is the String representation of a decimal value. So "10" is assumed to represent ten (decimal), not two (binary).

The next problem is that Long has a fixed length. You can't add an extra bit to it. You have to flip an existing bit.

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

testing:

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
jwvh
  • 50,871
  • 7
  • 38
  • 64