3

I have a string sequence from the output of an application which prints the control chars in "\x00" method. Example

\x00R50\x00\x00\x00\x01

I'm converting this to a scala string in REPL by inspecting the char one at a time and adding to a byte array.

scala> val ar:Array[Byte]=Array(0,82,53,48,0,0,1)
ar: Array[Byte] = Array(0, 82, 53, 48, 0, 0, 1)

scala> val a = ar.map(_.toChar).mkString
a: String = ?R50???

scala>

This seems to be laborious.. is there a quick way to convert \x00R50\x00\x00\x00\x01 to the val a as above?

stack0114106
  • 8,534
  • 3
  • 13
  • 38
  • Possible duplicate of [Java or Scala. How to convert characters like \x22 into String](https://stackoverflow.com/questions/47032049/java-or-scala-how-to-convert-characters-like-x22-into-string) – Kolmar Apr 30 '19 at 13:54
  • Did you check `new String(Array(0,82,53,48,0,0,1))` ? – Krzysztof Atłasik Apr 30 '19 at 13:59

2 Answers2

4

There is the constructor in java.lang.String :

public String(byte bytes[]) 
scala> new String(Array[Byte](0, 82, 53, 48, 0, 0, 1))
res0: String = ?R50???

Matthew I.
  • 1,793
  • 2
  • 10
  • 21
2

The input String only needs to be traversed once, but each Match goes through a few transitions.

val str = raw"\x00R50\x00\x00\x00\x01"

raw"\\x([0-9a-fA-F]{2})".r.replaceAllIn(str, m =>
    java.lang.Integer.parseInt(m.group(1),16).toChar.toString)
//res0: String = ?R50????

The value of each control char is preserved.

jwvh
  • 50,871
  • 7
  • 38
  • 64