Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of types when writing into BinaryWriter

Size of each character in ASCII (StreamWriter) takes 1 byte whether its a number or character.

Similarly what will be the size of each character, integer in binary? (BinaryWriter). Can some one explain in brief?

like image 346
hitesh jain Avatar asked Dec 18 '15 07:12

hitesh jain


People also ask

How does BinaryWriter work?

The BinaryWriter class provides methods that simplify writing primitive data types to a stream. For example, you can use the Write method to write a Boolean value to the stream as a one-byte value. The class includes write methods that support different data types.

What is binary Writer class in VB net?

The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor. The following table shows some of the commonly used methods of the BinaryWriter class.


1 Answers

Let's start with difference between StreamWriter and BinaryWriter. StreamWriter is for writing a textual representation to a stream. StreamWriter converts anything that is written (via Write* method) into a string, then converts via the encoding to bytes, and writes the bytes to the underlying stream.

BinaryWriter is for writing raw "primitive" data types to a stream. For numeric types it takes the in memory representation, does some work up to normalize the representation (e.g. to handle differences in endianess), and then writes the bytes to the underlying stream. Note that it also has an encoding provided in the constructor. This is used only for converting char and string into to bytes. The default encoding is UTF8.

Size of each character in ASCII (StreamWriter) takes 1 byte whether its a number or character.

This is statement is somewhat confusing to me. Let me clarify. The int 1 will be converted to the string "1" which encodes in ASCII as 49 which is indeed one byte, but 100 will be converted to the string "10000" which encodes in ASCII to 49 48 48 48 48, so that's 5 bytes. If using BinaryWriter both would occupy 4 bytes (the size of an int).

Similarly what will be the size of each character, integer in binary? (BinaryWriter). Can some one explain in brief?

The size of a char depends on the encoding used for both BinaryWriter and StreamWriter. The size of numeric types like int, long, double are the sizes of the underlying types, 4, 8, and 8 bytes respectively. The amount of data written is documented in each Write overload of BinaryWriter. Strings are treated distinctly from char[] in BinaryWriter and will have their length prefixed before the encoded bytes are written.

like image 73
Mike Zboray Avatar answered Oct 06 '22 10:10

Mike Zboray