I\'m writing a number converter. How can I convert a integer to a binary string in C# WITHOUT using built-in functions (Convert.ToString
does different things b
Simple soution:
IntToBinValue = Convert.ToString(6, 2);
At least part of the answer is to use decimal.GetBits(someValue)
to convert the decimal to its binary representation.
BitConverter.GetBytes
can be used, in turn, on the elements returned from decimal.GetBits()
to convert integers into bytes.
You may find the decimal.GetBits() documentation useful.
I'm not sure how to go from bytes to decimal, though.
Update: Based on Author's update:
BitConverter
contains methods for converting numbers to bytes, which is convenient for getting the binary representation. The GetBytes()
and ToInt32()
methods are convenient for conversions in each direction. The ToString()
overloads are convenient for creating a hexadecimal string representation if you would find that easier to interpret as 1's and 0's.
This is an unsafe implementation:
private static unsafe byte[] GetDecimalBytes(decimal d)
{
byte* dp = (byte*) &d;
byte[] result = new byte[sizeof(decimal)];
for (int i = 0; i < sizeof(decimal); i++, dp++)
{
result[i] = *dp;
}
return result;
}
And here is reverting back:
private static unsafe decimal GetDecimal(Byte[] bytes)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
if (bytes.Length != sizeof(decimal))
throw new ArgumentOutOfRangeException("bytes", "length must be 16");
decimal d = 0;
byte* dp = (byte*)&d;
byte[] result = new byte[sizeof(decimal)];
for (int i = 0; i < sizeof(decimal); i++, dp++)
{
*dp = bytes[i];
}
return d;
}
Here's mine: (The upper part convert 32-char binary string to 32-bit integer, the lower part convert 32-bit integer back to 32-char binary string). Hope this helps.
string binaryString = "011100100111001001110011";
int G = 0;
for (int i = 0; i < binaryString.Length; i++)
G += (int)((binaryString[binaryString.Length - (i + 1)] & 1) << (i % 32));
Console.WriteLine(G); //7500403
binaryString = string.Empty;
for (int i = 31; i >= 0; i--)
{
binaryString += (char)(((G & (1 << (i % 32))) >> (i % 32)) | 48);
}
Console.WriteLine(binaryString); //00000000011100100111001001110011
You can construct the representations digit by digit from first principles.
Not sure what built-in functions you don't want to use, but presumably you can construct a string character by character?
For one's complement and two's complement, calculate those with an additional step.
Or is this way too basic for what you need?
var a = Convert.ToString(4, 2).PadLeft(8, '0');