Skip to content

Instantly share code, notes, and snippets.

@fbettag
Created October 23, 2012 04:48
Show Gist options
  • Save fbettag/3936752 to your computer and use it in GitHub Desktop.
Save fbettag/3936752 to your computer and use it in GitHub Desktop.
UDP NetFlow 2 bytes to get Int/Long
def toLong(buf: Array[byte], offset: Int, length: Int) = {
var ret = 0L
var i = offset
while (i < offset + length) {
ret = ((ret << 8) & 0xffffffff) + (buf(i) & 0xff)
i += 1
}
ret
}
val myL = toLong(byteArray, 0, 2)
@Skyr
Copy link

Skyr commented Oct 23, 2012

Probably more functional...

def toLong2(buf: Array[Byte], offset: Int, length: Int):Long = {
  def toLong(pos: Int): Long =
    if (pos<offset) 0 else
    (toLong(pos-1) << 8) + buf(pos)
  toLong(offset+length-1)
}

...or even tail-recursive:

def toLong3(buf: Array[Byte], offset: Int, length: Int):Long = {
  @tailrec
  def toLong(pos: Int, ret: Long): Long =
    if (pos>=offset+length) ret else
    toLong(pos+1, (ret<<8) + buf(pos))
  toLong(offset, 0)
}

scnr, Martin's FP course does have some side effects ;-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment