Are there any equivalents of java floatToRawIntBits/intBitsToFloat (or doubleToRawLongBits/longBitsToDouble) in ruby?
Are there any equivalents of java floatToRawIntBits/intBitsToFloat (or doubleToRawLongBits/longBitsToDouble) in ruby?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
While there is not a simple alternative such as a
floatToRawIntBitsfunction, you could useArray#packandString#unpackto obtain the underlying bits:What’s going on here it’s you’re packing an array (we’re using an array with a single element, so we’re really packing just the element, i.e. 3.14) to a string that represents each byte with an ASCII character.
We then take each byte of the string (it’s the same as each character, because we’re using ASCII characters) and take the
String#ordof the character; in Ruby 1.9 characters are strings of a single element, andString#ordreturns the ordinal of a single character string.Using
Integer#to_s, with2as an argument, we get a binary representation of the ordinal, which is what we were searching for, the single bits of every byte of our float.Note that passing
'D'toArray#packmeans we want the bytes (what we get is characters in a string, but the method is really low-level enough to think in terms of bytes) that represent the element of the array as a double in native machine format. It’s important to pass the same parameter toString#unpackwhen getting back the number, because bytes are just bytes: the method doesn’t know anything about endianess, or about the data type.Check the docs for Array#pack and String#unpack for more info (especially regarding the correct byte order).
Edit: You can also get the underlying bits in a string form:
Edit 2: If you have some string read from a file, you can try with: