1. 程式人生 > >C# 整形轉成二進位制陣列

C# 整形轉成二進位制陣列

本章講述:整數-->二進位制-->儲存每位  nSub傳入的整數,關鍵程式碼

string byteB = "", byteC = "";
int[] array = new int[4];
int a = nSub;
if (a == 0)
	byteB = "0000";
while (a > 0)
{
	byteB += a % 2;
	a = a / 2;
}
if (byteB.Length < 4)
{
	int temp = 4 - byteB.Length;
	for (int ic = 0; ic < temp; ic++)
	{
		byteB += "0";
	}
}
for (int ibyte = byteB.Length - 1; ibyte >= 0; ibyte--)
{
	byteC += byteB[ibyte];
}

for (int ik = 0; ik < 4; ik++)
{
	int index4 = Convert.ToByte(byteC[ik]);
	if (index4 == 48)
	{
		index4 = 0;
		array[ik] = index4;
	}
	else
	{
		index4 = 1;
		array[ik] = index4;
	}
}
return array;