문제

A nibble is four bits. That means there are 16 (2^4) possible values. That means a nibble corresponds to a single hex digit, since hex is base 16. A byte is 2^8, which therefore can be represented by 2 hex digits, and consequently 2 nibbles.

So here below I have a 1 byte character:

'A'

That character is 2^8:

 'A'.unpack('B*')
 => ["01000001"] 

That means it should be represented by two hex digits:

 01000001 == 41

According to the Ruby documentation, for the Array method pack, when aTemplateString (the parameter) is equal to 'H', then it will return a hex string. But this is what I get back:

['A'].pack('H')
 => "\xA0" 

My first point is that's not the hex value it should return. It should have returned the hex value of 41. The second point is the concept of nibble, as I explained above, means for 1 byte, it should return two nibbles. But above it inserts a 0, because it thinks the input only has 1 nibble, even though 'A' is one byte and has two nibbles. So clearly I am missing something here.

도움이 되었습니까?

해결책

I think you want unpack:

'A'.unpack('H*') #=> ["41"]

pack does the opposite:

['41'].pack('H*') #=> "A"

다른 팁

It's tricky. ["1"].pack("H") => "\x10" and ["16"].pack("H") => "\x10". I spent long long time to understand this.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top