0

I'm trying to parse a string like this into a List[Byte].

Here is the string

"0x4e 0x01 0x09"

How can you instantiate a byte from a string representation?

4
  • What's the expected output for that example? Commented Jan 20, 2016 at 2:44
  • List(0x4e,0x010000000, 0x09) Commented Jan 20, 2016 at 2:46
  • That's a List[Int]. Commented Jan 20, 2016 at 2:46
  • You're right, simplifying the OP to use other data. Commented Jan 20, 2016 at 2:48

1 Answer 1

3

Here's one solution using a regex and parseInt.

def parseBytes(s: String): List[Byte] =
  (raw"\b0x([0-9a-f]{2})\b".r
    .findAllMatchIn(s)
    .map(g => Integer.parseInt(g.group(1), 16).toByte)
    .toList)

Test:

scala> parseBytes("0x4e 0x01 0x09 0xff")
0: List[Byte] = List(78, 1, 9, -1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.