1、int数组转化为byte数组
0x 16进制 0b二进制 2、任何数和1作与值不变 :0&1=0 1&1=1 任何数和0作与清0:1&0=0 0&0=0
public static byte [] itob(int [] intarr)
{
int bytelength=intarr.length*4;//长度
byte []bt=new byte[bytelength];//开辟数组
int curint=0;
for(int j=0,k=0;j<intarr.length;j++,k+=4)
{
curint= intarr[j];
bt[k]=(byte) ( (curint>>24)& 0b1111_1111);//右移4位,与1作与运算
bt[k+1]=(byte) ( (curint>>16)& 0b1111_1111);
bt[k+2]=(byte) ( (curint>>8)& 0b1111_1111);
bt[k+3]= (byte) ( (curint>>0 )& 0b1111_1111);
}
return bt;
}
2、byte数组转int数组
public static int [] btoi(byte [] btarr)
{
if(btarr.length%4!=0)
{
return null;
}
int [] intarr =new int [btarr.length/4];
int i1,i2,i3,i4;
for(int j=0,k=0;j<intarr.length;j++,k+=4)//j循环int k循环byte数组
{
i1=btarr[k];
i2=btarr[k+1];
i3=btarr[k+2];
i4=btarr[k+3];
if(i1<0)
{
i1+=256;
}
if(i2<0)
{
i2+=256;
}
if(i3<0)
{
i3+=256;
}
if(i4<0)
{
i4+=256;
}
intarr[j]=(i1<<24)+(i2<<16)+(i3<<8)+(i4<<0);//保存Int数据类型转换
}
return intarr;
}
3、两种读字符文件文件方式
BufferedReader br = new BufferedReader(new FileReader(path),1024 * 1024 * 10);
有中文时处理方式
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(pathIn),"GBK"));
/// <summary>
/// byte数组转int数组
/// </summary>
/// <param name="src">源byte数组</param>
/// <param name="offset">起始位置</param>
/// <returns></returns>
public static int[] bytesToInt(byte[] src, int offset)
{
int[] values=new int[src.Length/4];
for (int i = 0; i < src.Length / 4; i++)
{
int value = (int)((src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8)
| ((src[offset + 2] & 0xFF) << 16)
| ((src[offset + 3] & 0xFF) << 24));
values[i] = value;
offset += 4;
}
return values;
}
/// <summary>
/// int数组转byte数组
/// </summary>
/// <param name="src">源int数组</param>
/// <param name="offset">起始位置,一般为0</param>
/// <returns>values</returns>
public static byte[] intToBytes(int[] src,int offset)
{
byte[] values = new byte[src.Length*4];
for(int i = 0; i < src.Length; i++ )
{
values[offset+3] = (byte)((src[i] >> 24) & 0xFF);
values[offset+2] = (byte)((src[i] >> 16) & 0xFF);
values[offset+1] = (byte)((src[i] >> 8) & 0xFF);
values[offset] = (byte)(src[i] & 0xFF);
offset+=4;
}
return values;
}
c# uint[]和int[] 转 byte[]的几种方式
uint[] UintArray
byte[] ByteArray
1.for循环转
for(int i = 0;i<UintArray.lenth;i++){
ByteArray[i] = (byte)UintArray[i]
}
2.方式
ByteArray = Array.ConvertAll(UintArray, new Converter<uint, byte>(PointFToPoint));
public static byte PointFToPoint(uint UintArray)
{
return (byte)UintArray;
}
3.方式
ByteArray = UintArray.SelectMany(BitConverter.GetBytes).ToArray();
4.int[] 转byte[]
public static byte[] IntArrToByteArr(int[] intArr)
{
int intSize = sizeof(int) * intArr.Length;
byte[] bytArr = new byte[intSize];
//申请一块非托管内存
IntPtr ptr = Marshal.AllocHGlobal(intSize);
//复制int数组到该内存块
Marshal.Copy(intArr, 0, ptr, intArr.Length);
//复制回byte数组
Marshal.Copy(ptr, bytArr, 0, bytArr.Length);
//释放申请的非托管内存
Marshal.FreeHGlobal(ptr);
return bytArr;
}