Convert int to binary
I'm trying to make a unit conversion application, and I can't figure out how to convert int to binary. My code is:
if (oneDecimalBool == true && twoBinaryBool == true) {
var value = inputOneText.text;
value = System.Convert.ToString (value, 2);
}
I know I'm probably making this too confusing, but I'm getting these two errors.
![alt text][1]
(sorry if the image is hard to read)
if anyone knows how to fix this please let me know. [1]: /storage/temp/82852-screen-shot-2016-11-25-at-91354-pm.png
Answer by NoseKills · Nov 26, 2016 at 08:42 AM
I think you are confusing yourself a bit by using the var
keyword here. It hides the fact that the type of value
is string
(because that's the type you assign to it - UnityEngine.UI.Text.text.
System.Convert.ToString ()
doesn't have an overload that takes parameters of type (string, int)
and that's what the error is saying. You probably meant to call it with (int, int)
, but in order to do so, you have to convert the value of inputOneText.text
to an int. Afterall, the user could type "car" in the textfield, and that's pretty difficult to convert to a binary number. Setting the textfield input to allow only numbers doesn't change the type of Text.text
variable.
Use either of these methods to convert your text to a number.
So I found a video (https://www.youtube.com/watch?v=sBYfIpECQec) and from it I changed my code to look like this. string inputNumber = inputOne.text; int x; if (int.TryParse (inputNumber, out x)) {
valueTwoText.text = System.Convert.ToString(inputNumber, 2);
} else {
valueTwoText.text = "Invalid Number";
}
However, I am still getting the same error. Do you know why?
You should have used
System.Convert.ToString(x, 2);
inputNumber is still your string variable ^^.
Thanks! Do you think it would it be possible to have decimals?