Search code examples
smalltalkpharo

Convert a float in Pharo Smalltalk to a bytearray?


I am using Pharo Smalltalk 2.0. I need to convert a float into a ByteArray. There seems to be no method to do this, is there a roundabout way of doing it?

For instance, 1 asFloat asByteArray would be perfect.

Context: I'm trying to send binary data through websocket using the Zinc Websocket package.


Solution

  • If you are on i386 CPU, you can do it with native boost

    (ByteArray new: 8) nbFloat64AtOffset: 0 put: Float pi; yourself
    

    Note that byte order is littleEndian in this case.

    Otherwise, you have those platform independent access:

    (ByteArray new: 8) doubleAt: 1 put: Float pi bigEndian: true ; yourself
    

    Note the difference with 0-based index for first case, and 1-based for second case.