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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With