等效于将字节数组转换成二进制字符串表示,然后将其中为1的位置组成一个整型数组。
不过第一个位置值不是0,而是1。
我写了两种实现方式,大家看看如何?看看有没有更优的方式。方法一:public static int[] byte2key(byte[] bytes)
{
int[] keylist = new int[256];
int i = 0;
int j = 0;
int k = 0;
int left;
int fac;
foreach (byte bytekey in bytes)
{
j = 1;
left = (int)bytekey;
fac = 128;
while (left > 0)
{
if (left >= fac)
{
keylist[k] = i * 8 + j;
left -= fac;
k++;
}
fac /= 2;
j++;
}
i++;
}
Array.Resize(ref keylist, k);
return keylist;
}方法二:public static int[] byte2key(byte[] bytes)
{
StringBuilder bin = new StringBuilder();
foreach (byte bitem in bytes)
{
bin.Append(Convert.ToString(bitem, 2).PadLeft(8, '0'));
}
string strbin = bin.ToString();
int[] keylist = new int[256];
int i = 0;
int key = strbin.IndexOf('1');
while (key >= 0)
{
key++;
keylist[i] = key;
i++;
key = strbin.IndexOf('1', key);
}
Array.Resize(ref keylist, i);
return keylist;
}
不过第一个位置值不是0,而是1。
我写了两种实现方式,大家看看如何?看看有没有更优的方式。方法一:public static int[] byte2key(byte[] bytes)
{
int[] keylist = new int[256];
int i = 0;
int j = 0;
int k = 0;
int left;
int fac;
foreach (byte bytekey in bytes)
{
j = 1;
left = (int)bytekey;
fac = 128;
while (left > 0)
{
if (left >= fac)
{
keylist[k] = i * 8 + j;
left -= fac;
k++;
}
fac /= 2;
j++;
}
i++;
}
Array.Resize(ref keylist, k);
return keylist;
}方法二:public static int[] byte2key(byte[] bytes)
{
StringBuilder bin = new StringBuilder();
foreach (byte bitem in bytes)
{
bin.Append(Convert.ToString(bitem, 2).PadLeft(8, '0'));
}
string strbin = bin.ToString();
int[] keylist = new int[256];
int i = 0;
int key = strbin.IndexOf('1');
while (key >= 0)
{
key++;
keylist[i] = key;
i++;
key = strbin.IndexOf('1', key);
}
Array.Resize(ref keylist, i);
return keylist;
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货