Kamlesh Arya Kamlesh Arya - 1 year ago 133
Ruby Question

To convert ruby unpack equivalent in java

I'm trying to understand this line of ruby code:


which is converting




As far as I understand this, it is base64 to hex conversion, but when I try to do the same thing, its not matching with converted one.

I need to implement the same functionality in Java.

Answer Source

So I'm going to break this down. The first step is token.unpack('m0'). According to Idiosyncratic Ruby unpack('m0') will decode base64, similarly to the built-in Base64 libararies Base64.decode64(string) function. But unpack returns an arry here, with only 1 element, the converted base64. So we use token.unpack('m0').first to get the first (and in this case the only) element of the array returned by token.unpack('m0'). If this was all, then you'd be correct to say that it's just base64. But, the unpacked base64 is unpacked again, this time with 'H*', which will convert the characters to hex. And finally, because that will return an array, you use first again to make it only a string.

So in summary, what is happening is that first your string is being decoded from base64 to a string, then it's being converted to hex.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download