How to convert integer to binary string in C#?

前端 未结 8 1995
失恋的感觉
失恋的感觉 2020-12-02 01:48

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

8条回答
  •  一整个雨季
    2020-12-02 02:25

    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;
        }
    

提交回复
热议问题