1. 程式人生 > >C# 字串到位元組陣列,位元組陣列轉整型

C# 字串到位元組陣列,位元組陣列轉整型

            int num = 12345;
            string num1 = Convert.ToString(12345, 16);
            byte[] bytes = BitConverter.GetBytes(num);//將int32轉換為位元組陣列
            num = BitConverter.ToInt32(bytes, 0);//將位元組陣列內容再轉成int32型別

 

            string no = DateTime.Now.ToString("yyyyMMddhhmmssfff"); //時間轉字串
            Console.WriteLine(no);

 

        private void button1_Click(object sender, EventArgs e)
        {


            // //字串到16進位制
            // string s = "I have";
            // string sHex = "";
            // byte[] sbytes = Encoding.Default.GetBytes(s);
            // for (int i = 0; i < sbytes.Length; i++)
            
// { // sHex += sbytes[i].ToString("X2") + " "; // } // //整型到16進位制 // int i25 = 25; // string i25Hex = ""; // i25Hex = i25.ToString("X2"); // //浮點數到16進位制 // double d = 3.14157; // string dHex = ""; // //
dHex = d.ToString("X2");//報錯 // byte[] dbytes = Encoding.Default.GetBytes(d.ToString()); // for (int i = 0; i < dbytes.Length; i++) // { // dHex += dbytes[i].ToString("X2") + " "; // } // bool b = true; // string bHex = ""; // //create the file // BinaryWriter bw = new BinaryWriter(new FileStream("mydata", FileMode.Create)); // //bw.Write(i25);//寫入1個25 //// bw.Write(d); //// bw.Write(b); // bw.Write(s);//寫入一個字串 // bw.Close(); // MessageBox.Show("ccc"); //reading from the file BinaryReader br = new BinaryReader(new FileStream("mydata.pdf", FileMode.Open)); //var i25 = br.ReadInt32(); //var d = br.ReadDouble(); //var b = br.ReadBoolean(); // var A0 =br.ReadByte(); //讀取一個位元組(第一個FF(25)(10進位制)37) //byte[] bytes = new byte[1000];//每個值為0 //for (int i = 0; i < bytes.Length;i++ ) //{ // bytes[i] = br.ReadByte(); //} br.BaseStream.Seek(6236060, SeekOrigin.Begin);// 定位到第6236060個位元組 var test = br.BaseStream.Length - br.BaseStream.Position;//總長度-當前位置, 可能是讀取到最後 byte[] bytes = br.ReadBytes((int)test); while (br.BaseStream.Position < br.BaseStream.Length) { // bytes[i] = br.ReadByte(); //讀取到最後 } using (BinaryReader br = new BinaryReader(fs)) { while (br.PeekChar() > -1) { // bytes[i] = br.ReadByte(); //讀取到最後 } } //var s1 = br.ReadString(); MessageBox.Show("ccc"); string str = System.Text.Encoding.Default.GetString(bytes); br.Close(); } public void F1() { string path = @"C:\a.txt"; FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); char cha; int num; double doub; string str; try { while (true) { cha = br.ReadChar();//從當前流中讀取下一個字元 num = br.ReadInt32(); //從當前流中讀取4位元組有符號整數 doub = br.ReadDouble(); //從當前流中讀取8位元組浮點值 str = br.ReadString();//從當前流中讀取一個字串 Console.WriteLine("{0},{1},{2},{2}", cha, num, doub, str); } } catch (EndOfStreamException e) { Console.WriteLine(e.Message); Console.WriteLine("已經讀到末尾"); } finally { Console.ReadKey(); } }