0

The title says it all, what is the easiest way to flip the endianness of a byte in Scala?

Edit: Here is an example of a hex string that can be converted to a List[Byte] for what I am talking about

"44[5e405f7b46d912b50ea59d0f0962ed9e251042a4b31208315c406a4aa962]ff" was not equal to "44[e504f5b7649d215be05ad9f09026dee95201244a3b218013c504a6a49a26]ff"
Chris Stewart
  • 1,641
  • 2
  • 28
  • 60
  • 1
    Endianness usually refers to byte order within a multibyte sequence, ie, do the bytes for a 32-bit integer appear as [0,0,0,1] or [1,0,0,0] for the integer value 1. Do you mean flipping a byte from 0x01 to 0x80 (0000001 to 10000000), for instance? – DPM Jan 14 '16 at 21:03
  • I'm editted the OP. It's a hex string now but i'll add the List of bytes – Chris Stewart Jan 14 '16 at 21:05
  • You would manipulate the endianness in Scala the same way was you [would in Java](http://stackoverflow.com/questions/3842828/converting-little-endian-to-big-endian). – Castaglia Jan 14 '16 at 21:39

1 Answers1

2

If you mean flipping low with high half-bits of a Byte:

(b: Byte) => (b >>> 4) + (b << 4)

If you want to flip every half-byte on a hex string I would grouped by 2 characters then flip the pairs before creating the string back again:

val input = "44[5e405f...".replaceAll("[^0-9a-f]","")
val expected = "44[e504f5...".replaceAll("[^0-9a-f]","")

// as suggested by @PaulDraper in the comments
input.grouped(2).map(_.reverse).mkString == expected

// or the verbose    
val ab = "(.)(.)".r
input.grouped(2).map { case ab(a, b) => b ++ a }.mkString == expected

If your input is a List[Byte]:

val inputBytes = input.grouped(2).map(Integer.parseInt(_, 16).toByte)
val expectedBytes = expected.grouped(2).map(Integer.parseInt(_, 16).toByte)

inputBytes.map((b: Byte) => (b >>> 4) + (b << 4)).map(_.toByte).toSeq == expectedBytes.toSeq
Filippo Vitale
  • 7,597
  • 3
  • 58
  • 64