2016-01-20 76 views
0

我試圖將這樣的字符串解析爲List[Byte]將字節字符串解析爲本地斯卡拉字節

這裏是

"0x4e 0x01 0x09" 

你怎麼可以實例從一個字符串表示的字節串?

+0

什麼是對於例如預期的輸出? –

+0

List(0x4e,0x010000000,0x09) –

+0

這是一個'List [Int]'。 –

回答

3

這是一個使用正則表達式和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) 

測試:

scala> parseBytes("0x4e 0x01 0x09 0xff") 
0: List[Byte] = List(78, 1, 9, -1)