Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ascii range regards binary files?

ive been reading about this topic and didnt get the specific info for my question :

(maybe the following is incorrect - but please do correct me)

Every file( text/binary) is saving BYTES.

byte is 8 bits hence max value is 2^8-1 = 255 codes.

those 255 codes divides to 2 groups:

0..127 : textual chars
128:..255 : special chars.

so binary file contains char codes from the whole range : 0..255 ( ascii chars+special chars).

1 ) correct ?

2) NOw , lets say im saving one INT in binary file. ( 4 byte in 32 bit system)

how does the file tells the progem reads it : its not 4 single unrelated bytes but an int which is 4 bytes ?

like image 580
Royi Namir Avatar asked Feb 17 '26 16:02

Royi Namir


1 Answers

Underlying all files are being stored as bytes, so in a sense what you're saying is correct. However, if you open a file that's intended to be read as binary and try to read it in a text editor, it will look like gibberish.

How does a program know whether to read a file as text or as binary? (ie as special sets of ASCII or other encoded bytes, or just as the underlying bytes with a different representation)?

Well, it doesn't know - it just does what it's told.

In Windows, you open .txt files in notepad - notepad expects to be reading text. Try opening a binary file in notepad. It will open, you will see stuff, but it will be rubbish.

If you're writing your own program you can write using BinaryWriter and read using BinaryReader if you want to store everything as binary. What would happen if you wrote using BinaryWriter and read using StringReader?


To answer your specific example:

using (var test = new BinaryWriter(new FileStream(@"c:\test.bin", FileMode.Create)))
{
    test.Write(10);
    test.Write("hello world");
}

using (var test = new BinaryReader(new FileStream(@"c:\test.bin", FileMode.Open)))
{
    var out1 = test.ReadInt32();
    var out2 = test.ReadString();

    Console.WriteLine("{0} {1}", out1, out2);
}

See how you have to read in the same order that's written? The file doesn't tell you anything.

Now switch the second part around:

using (var test = new BinaryReader(new FileStream(@"c:\test.bin", FileMode.Open)))
{
    var out1 = test.ReadString();
    var out2 = test.ReadInt32();

    Console.WriteLine("{0} {1}", out1, out2);
}

You'll get gibberish out (if it works at all). Yet there is nothing you can read in the file that will tell you that beforehand. There is no special information there. The program must know what to do based on some out of band information (a specification of some sort).

like image 198
yamen Avatar answered Feb 19 '26 04:02

yamen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!