开发者

Using unpack to write a byte array with hex characters?

开发者 https://www.devze.com 2022-12-08 09:40 出处:网络
I want to take a value like: ff0000 and make it into a byte array containing those hex values: 开发者_如何学Go\\xff\\x00\\x00

I want to take a value like:

ff0000

and make it into a byte array containing those hex values:

开发者_如何学Go\xff\x00\x00

I'm not clear on how to do this using str.unpack


"ff0000".scan(/../).map { |match| match.hex } #=> [255, 0, 0]

or

("ff0000".scan(/../).map { |match| match.hex }).pack('C*') #=> "\377\000\000"

Depending on what format you want it in.


I'm not sure unpack can do this. Try this instead:

"ff0000".gsub(/../) { |match| match.hex.chr }
0

精彩评论

暂无评论...
验证码 换一张
取 消