Stream 和 byte[] 之间的转换
/* - - - - - - - - - - - - - - - - - - - - - - - -
* Stream 和 byte[] 之间的转换
* - - - - - - - - - - - - - - - - - - - - - - - */
/// <summary>
/// 将 Stream 转成 byte[]
/// </summary>
public byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
/// <summary>
/// 将 byte[] 转成 Stream
/// </summary>
public Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
/* - - - - - - - - - - - - - - - - - - - - - - - -
* Stream 和 文件之间的转换
* - - - - - - - - - - - - - - - - - - - - - - - */
/// <summary>
/// 将 Stream 写入文件
/// </summary>
public void StreamToFile(Stream stream,string fileName)
{
// 把 Stream 转换成 byte[]
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
// 设置当前流的位置为流的开始
stream.Seek(0, SeekOrigin.Begin);
// 把 byte[] 写入文件
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(bytes);
bw.Close();
fs.Close();
}
/// <summary>
/// 从文件读取 Stream
/// </summary>
public Stream FileToStream(string fileName)
{
// 打开文件
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
// 读取文件的 byte[]
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
// 把 byte[] 转换成 Stream
Stream stream = new MemoryStream(bytes);
return stream;
}
List<string>和string[]数组之间的相互转换
//从System.String[]转到List<System.String>
System.String[] str={"str","string","abc"};
List<System.String> listS=new List<System.String>(str);
// 从List<System.String>转到System.String[]
List<System.String> listS=new List<System.String>();
listS.Add("str");
listS.Add("hello");
System.String[] str=listS.ToArray();
测试如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
System.String[] sA = { "str","string1","sting2","abc"};
List<System.String> sL = new List<System.String>();
for (System.Int32 i = 0; i < sA.Length;i++ )
{
Console.WriteLine("sA[{0}]={1}",i,sA[i]);
}
sL = new List<System.String>(sA);
sL.Add("Hello!");
foreach(System.String s in sL)
{
Console.WriteLine(s);
}
System.String[] nextString = sL.ToArray();
Console.WriteLine("The Length of nextString is {0}",nextString.Length);
Console.Read();
}
}
}
进行上位机与PLC进行通讯时,分析协议时需要用到进制转换内容,做此记录方便以后进行查阅;
private void button1_Click(object sender, EventArgs e)
{
float value = 0.1f;
string hex = string.Empty;
ShowFloatToHex(ref value, ref hex);
ShowHexToFloat(ref hex, ref value);
string input = "3DCCCCCD";
string[] InBuffrr = new string[20];
char[] values = input.ToCharArray();
int i = 0;
foreach (char letter in values)
{
int value1 = Convert.ToInt32(letter);
string hexOutput = String.Format("{0:X}", value1);
InBuffrr[i] = hexOutput;
i = i + 1;
}
string hexString = "3DCCCCCD";
int num = int.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier);
byte[] floatVals = BitConverter.GetBytes(num); //以十进制倒着放入数组
float f22 = BitConverter.ToSingle(floatVals, 0); //十六进制=>浮点数
float floatValue = 0.1f;
byte[] bytes = BitConverter.GetBytes(floatValue);//浮点数转数组:
float f33 = BitConverter.ToSingle(bytes, 0);
int d = 16;
var id1 = Convert.ToInt32("FF", 16); //十六进制=>十进制
var id2 = Convert.ToInt64("FF", 16);
var a = System.Convert.ToString(22, 2); //十进制=>二进制 ok
var c = System.Convert.ToString(0x11, 2); //十六进制=>二进制 ok
var d1 = System.Convert.ToInt32("1111", 2); //二进制=>十进制 ok
var r = System.Convert.ToString(0xa2, 10); //十六进制=>十进制 ok
var t = System.Convert.ToInt32("0x41", 16); //十六进制=>十进制 ok
var e1 = string.Format("{0:X}", System.Convert.ToInt32("1111", 2)); //二进制转十六进制 ok
int s = 12;
var f = s.ToString("X"); //十进制=>十六进制
var f1 = string.Format("{0:X}", s); //大写对大写X x
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InControls.PLC.FX
{
public static class FxConvert
{
/// <summary>
/// 16进制字符转换为对应的10进制值
/// </summary>
/// <param name="c"> 0-9,A-F </param>
/// <returns>返回对应的 0- 15 </returns>
public static int HexToDec (char c)
{
int v = (int)c;
if(v >= (int)'0' && v <= (int)'9') {
return (v - (int)'0');
} else if(v >= (int)'A' && v <= (int)'F') {
return (v - (int)'A' + 10);
} else if(v >= (int)'a' && v <= (int)'f') {
return (v - (int)'a' + 10);
}
return 0;
}
/// <summary>
/// 16进制Byte转换为对应的10进制值
/// </summary>
/// <param name="b"> '0'-'9','A'-'F' </param>
/// <returns>返回对应的 0- 15 </returns>
public static int HexToDec (byte b)
{
if(b >= '0' && b <= '9')
return b - (byte)'0';
else if(b >= 'A' && b <= 'F')
return b - (byte)'A' + 10;
else if(b >= 'a' && b <= 'f')
return b - (byte)'a' + 10;
else
return (0);
}
/// <summary>
/// 16进制字符串转换为对应的10进制值
/// </summary>
/// <param name="s">16进制字符串</param>
public static int HexToDec (string s)
{
int result;
int.TryParse(s, System.Globalization.NumberStyles.HexNumber, null, out result);
return result;
}
public static int HexToDec (byte[] data, int fromIndex, int bytes)
{
int result = 0;
for(int i = fromIndex; i < Math.Min(data.Length, fromIndex + bytes); i++) {
result = result * 16 + HexToDec(data[i]);
}
return (result);
}
/// <summary>
/// 16进制串转换为对应的2进制描述格式
/// 例如输入 "1A",则返回“00011010”
/// </summary>
/// <param name="s">待转换的16进制串</param>
/// <returns>返回的二进制描述串</returns>
public static string HexToBin (string hexString)
{
string result = string.Empty;
for(int i = 0; i < hexString.Length; i++) {
char c = hexString[i];
int b = HexToDec(c);
string s = Convert.ToString(b, 2);
if(s.Length != 4)
s = new string('0', 4 - s.Length) + s;
result += s;
}
return (result);
}
/// <summary>
/// 数值转换为16进制字符串
/// </summary>
/// <param name="v">数值</param>
/// <returns>对应的16进制串</returns>
public static string DecToHex (uint v)
{
StringBuilder sb = new StringBuilder(8);
sb.AppendFormat("{0:X}", v);
if(sb.Length % 2 == 1)
return ("0" + sb.ToString());
else
return sb.ToString();
}
/// <summary>
/// 数值转换为16进制字符串
/// </summary>
/// <param name="v">数值</param>
/// <param name="width">返回的字符串的字符数</param>
/// <returns>对应的16进制串</returns>
public static string DecToHex (uint v, int width)
{
string s = string.Format("{0:X}", v);
if(width > s.Length) {
string s0 = new string('0', width - s.Length);
s = s0 + s;
}
return (s);
}
/// <summary>
/// 10进制字符串转换为值
/// </summary>
public static uint DecToValue (string s)
{
uint v = 0;
for(int i = 0; i < s.Length; i++) {
v = v * 10 + (uint)((char)s[i] - (char)'0');
}
return v;
}
/// <summary>
/// 8进制字符串转换为值
/// </summary>
public static uint OctToValue (string s)
{
uint v = 0;
for(int i = 0; i < s.Length; i++) {
v = v * 8 + (uint)((char)s[i] - (char)'0');
}
return v;
}
/// <summary>
/// 将给定字符串转换为16进制串
/// 例如将 “1234”转换为“31323334”
/// </summary>
public static string ToHexString (string source)
{
StringBuilder sb = new StringBuilder(source.Length * 2);
for(int i = 0; i < source.Length; i++) {
char c = source[i];
sb.Append(DecToHex(c));
}
return (sb.ToString());
}
}
}
//高低位互换
private static string strConvert(string strValue)
{
int intLength = strValue.Length;
string res = string.Empty;
for (int i = 0; i < intLength / 2; i++)
{
res += strValue.Substring(intLength - 2 * (i + 1), 2);
}
return res;
}
//字符串转换为二进制数据:
byte[] bytes = new byte[str.Length / 2];
for (int i = 0; i < str.Length; i += 2)
bytes[i / 2] = (byte)Convert.ToByte(str.Substring(i, 2), 16);
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i )
{
returnStr = bytes[i].ToString("X2");
}
}
return returnStr;
}
public static String bytes2HexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = "0" + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
/// <summary>
/// 字符串转换16进制字节数组
/// </summary>
/// <param name="hexString">输入的字符串</param>
/// <returns>字节数组</returns>
private static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString = " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i )
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
Int32 与byte互转
* int到byte[] 由高位到低位
* @param i 需要转换为byte数组的整行值。
* @return byte数组
*/
public static byte[] intToByteArray(int i)
{
byte[] result = new byte[4];
result[0] = (byte)((i >> 24) & 0xFF);
result[1] = (byte)((i >> 16) & 0xFF);
result[2] = (byte)((i >> 8) & 0xFF);
result[3] = (byte)(i & 0xFF);
return result;
}
/**
* byte[]转int
* @param bytes 需要转换成int的数组
* @return int值
*/
public static int byteArrayToInt(byte[] bytes)
{
int value = 0;
for (int i = 0; i < 4; i++)
{
int shift = (3 - i) * 8;
value += (bytes[i] & 0xFF) << shift;
}
return value;
}
//FloatToHex方法可以把浮点数转换成32位的二进制数
private static string FloatToHex(float value)
{
byte[] bytes = BitConverter.GetBytes(value);
StringBuilder stringBuffer = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
if (i != 0)
{
stringBuffer.Insert(0, " ");
}
string hex = Convert.ToString(bytes[i], 2);
stringBuffer.Insert(0, hex);
// 位数不够补0
for (int j = hex.Length; j < 8; j++)
{
stringBuffer.Insert(0, "0");
}
}
return stringBuffer.ToString();
}
//HexToFloat方法可以把32 位的二进制转化为4个字节8位的16进制
public static float HexToFloat(string str)
{
str = str.Replace(" ", string.Empty);
if (str.Length != 32)
{
Console.WriteLine("数据长度错误");
return float.NaN;
}
byte[] intBuffer = new byte[4];
// 将二进制串按字节逆序化(一个字节8位)
for (int i = 0; i < 4; i++)
{
string hex = str.Substring(24 - 8 * i, 8);
intBuffer[i] = Convert.ToByte(hex, 2);
}
return BitConverter.ToSingle(intBuffer, 0);
}
private static void ShowFloatToHex(ref float value, ref string hex)
{
hex = FloatToHex(value);
MessageBox.Show(value + " = " + hex);
}
private static void ShowHexToFloat(ref string hex, ref float value)
{
value = HexToFloat(hex);
MessageBox.Show(hex + " = " + value);
}
//两个short转flaot
byte[] bytes = new byte[4];
int[] readHoldingRegisters1 = { 26214, 16782 };
for (int i = 0; i < readHoldingRegisters1.Length; i++)
{
BitConverter.GetBytes((short)readHoldingRegisters1[i]).CopyTo(bytes, i * 2); //复制到一个数组内
}
//字节转float
float f33 = BitConverter.ToSingle(bytes, 0);