Search Unity

Decimal number to Binary

Discussion in 'Scripting' started by Shayke, Dec 8, 2018.

  1. Shayke

    Shayke

    Joined:
    Dec 8, 2017
    Posts:
    352
    Hi, i am asking the player to put a number, for example 14.125 and i need to convert it without using arrays.
    14.125 should be 1110.001
    Any ideas?
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,770
  3. Shayke

    Shayke

    Joined:
    Dec 8, 2017
    Posts:
    352
  4. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,770
    You can convert string back to int.
     
  5. Shayke

    Shayke

    Joined:
    Dec 8, 2017
    Posts:
    352
    Can't bro
    It is a class excercise and we have some demands
     
  6. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,770
    Just ask your self question, how you going represent binary number as single char? (if even think of using it)
    string is an array of chars.
     
  7. Shayke

    Shayke

    Joined:
    Dec 8, 2017
    Posts:
    352
    lol no arrays and no strings man
     
  8. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,770
    hence no char.
    Did you try look up for answer on the net?
     
  9. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Just do the math directly.

    Hints for a trivial approach:
    - optionally, you can break the problem into two parts: integer part, decimal places. If you want to break them up: one cast to int, then substract the integer from the floating point value in order to get the decimal parts.

    - binary is just some math with 2^n where n is an integer. Though, don't start using Math.Pow, instead use shift operators

    - extracting the bits can either be done with bit wise operations or simple math operations like division (for the latter you will need the remainder once at the end)

    - both can be done in a loop while you keep changing the n in 2^n and do the operations.

    The decimal places can be done in a similar fashion.

    Those are just two of many available approaches. Depending on the language you could also work on the memory level directly.

    Not sure though why you ask this in a game dev forum.
     
  10. Shayke

    Shayke

    Joined:
    Dec 8, 2017
    Posts:
    352
    Thanks for your response, i found a solution.
    I ask it here because it is about scripting and this is the forum i am use to.
    :)