Decimal to binary converter

You can check invidual bits this expression:


n & FMath::Pow(2,x)

n being a number and x being bit you check (not sure about 0 position, which should be first bit will work with pow… but there way to avoid it). How does it work? & is a AND gate operator, all power of 2 numbers and number 1 are 1 in invidual bit position in binery form ( 1=1, 2=10, 4=100, 8=1000) so if you do AND gate operation on series of bits againts 1 bit on specific position, it will return 0 if that invidual bit is 0. So in UE you can do this this way:



FString FMyFanctMath::BitsToString(int32 n){

       FString Bits;
       Bits.Reserve(FMath::FloorToInt(FMath::Sqrt(n))); //Reserveing space for string in memory FString won't rellocate string multiple times in process
       //We multiply by 2 until it's bigger then n where every bit will be 0 after that
       for(i = 1;i<n;i*2) {
         if(n & i) Bits.Append("1");
         else Bits.Append("0");
       }
       return Bits.Reverse() //We need to reverse bit order, so smallest is last
}


Obviuesly you can only present binery number in string, since any number is a number and can be presented in any form, UE4 presents number only in decimals, or else there also function for hex

C++14 allows to use binery form numbers in code, using “0b” prefix (same as “0x” for hex), but UE4 uses C++11 compiler mode if i’m not mistaken, so it won’t work in UE4

1 Like