phpInDev

get_binary

string get_binary ( int number )

Returns the given number as binary (as represented by GM). The number is converted to binary using the binary functions inside GM, so the return value should basically be exactly as GM represents the given number in binary. This function could be useful when dealing with binary values of numbers.

The returned value is the binary of the number as string. Note that only positive numbers are accepted, since GM doesn't handle binary shift of negative numbers properly.

Example 1. using get_binary

{ show_message(get_binary(1024)); show_message(get_binary(1023)); show_message(get_binary(783)); }

Shows messages:

10000000000 1111111111 1100001111

Code for get_binary.gml

{
    var retval;
    
    argument0 = floor(abs(argument0));
    retval = "";
    
    if (argument0 == 0)
    {
        return "0";
    }
    
    while (argument0)
    {
        // Add 1 or 0 depending on the bit
        if (argument0 & 1)
        {
            retval = "1" + retval;
        }
        else
        {
            retval = "0" + retval;
        }
        
        // Remove one bit
        argument0 = argument0 >> 1;
    }
    
    return retval;
}