jjccx

jjccx's blog
posts - 31, comments - 97, trackbacks - 5, articles - 70
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

公告

从文件按位读出

Posted on 2004-12-16 13:05 jjccx 阅读(208) 评论(0)  编辑 收藏
using System;
using System.IO;

namespace bbbbbbb
{
    
/// <summary>
    
/// Class1 的摘要说明。
    
/// </summary>

    class Class1
    
{
        
/// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>

        [STAThread]
        
static void Main(string[] args)
        
{
            
string FILE_NAME = "Test.data";

            FileStream fs 
= new FileStream(FILE_NAME, FileMode.OpenOrCreate);
            
// Create the writer for data.
            BinaryWriter w = new BinaryWriter(fs);
            
// Write data to Test.data.
            for (int i = 0; i < 11; i++
            
{
                w.Write( (
byte) i);
                
//w.Write( (int) i);
            }

            w.Close();
            fs.Close();
            
// Create the reader for data.
            fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
            BinaryReader r 
= new BinaryReader(fs);
            
// Read data from Test.data.
            byte b;
            
for (int i = 0; i < 11; i++
            
{
                b  
= r.ReadByte();
                Console.WriteLine(Convert.ToString(b, 
2).PadLeft(8'0'));
            }

            w.Close();
        }


        
protected static string BinToString(byte myByte)
        
{
            
return
                (((myByte 
& 0x80!= 0? "1" : "0"+
                (((myByte 
& 0x40!= 0? "1" : "0"+
                (((myByte 
& 0x20!= 0? "1" : "0"+
                (((myByte 
& 0x10!= 0? "1" : "0"+
                (((myByte 
& 0x8!= 0? "1" : "0"+
                (((myByte 
& 0x4!= 0? "1" : "0"+
                (((myByte 
& 0x2!= 0? "1" : "0"+
                (((myByte 
& 0x1!= 0? "1" : "0");
        }

    }

}