0

Here is my specific problem. I need to represent an integer (like 1,2,3,..) as a binary literal with exactly 128 bits.

This is my string representing 1 in binary: string = "000...0001"; // 128 characters. all zeros until the last 1

Intended result: bx000...0001;

This issue is that 128 bits is larger than normal types like int, double, decimal, etc. Thus, I believe you must use the BigInteger class to hold this binary value??

Another way to frame this: How can I make sure my BigInteger value is 16 bytes big?

BigInteger val = new BigInteger(1); // but must be 16 bytes exactly.

jburcham
  • 1
  • 1

2 Answers2

0

You would have to specify the number of bytes and pad whatever is missing with 0's, then you can use the BitArray to get the bit values. Something like this.

public static string GetBitString(BigInteger val, int bytes)
{
    byte[] arrayBytes = new byte[bytes];
    var valBytes = val.ToByteArray();
    for (var i = 0; i < valBytes.Length; i++)
    {
        arrayBytes[i] = valBytes[i];
    }
    var arr = new BitArray(arrayBytes);
    return $"bx{string.Join("", arr.Cast<bool>().Reverse().Select(c => c ? "1" : "0"))}";
}

Another options is to just resize the array created to be 16 bytes. Something like this

public static string GetBitString(BigInteger val, int bytes)
{
    var valBytes = val.ToByteArray();
    Array.Resize(ref valBytes, bytes);
    return $"bx{string.Join("", new BitArray(valBytes).Cast<bool>().Reverse().Select(c => c ? "1" : "0"))}";
}
hawkstrider
  • 4,141
  • 16
  • 27
0

Using the ToBinaryString extension method from this answer modified to skip leading zeros and not force a sign zero, you can just use PadLeft to ensure you have leading zeroes:

public static string ToBinaryString(this BigInteger bigint) {
    var bytes = bigint.ToByteArray();

    // Create a StringBuilder having appropriate capacity.
    var base2 = new StringBuilder(bytes.Length * 8);

    // Convert remaining bytes adding leading zeros.
    var idx = bytes.Length - 1;
    for (; idx > 0 && bytes[idx] == 0; --idx)
        ;
    for (; idx >= 0; --idx)
        base2.Append(Convert.ToString(bytes[idx], 2).PadLeft(8, '0'));

    return base2.ToString();
}

Then with the prefix and the left padding:

var ans = "bx"+val.ToBinaryString().PadLeft(128, '0');
NetMage
  • 26,163
  • 3
  • 34
  • 55