Not sure how the byte[] works in Csharp
Hi, basically I have a very simple program which I'm using to try and understand how bytes work:
It is my understanding that the integers printed should be the 4 ascii values for "Test" and nothing more, instead this is printed (grouped into sets of 4 for easier reading):
And I am unsure as to why, could anyone be of assistance please
5 Replies
First of all, don't use BinaryFormatter for anything. Second of all, BinaryFormatter is not doing a direct conversion to bytes, it has its own format.
To convert text to bytes use the appropriate Encoding class
mtreit#6470
REPL Result: Success
Console Output
Compile: 568.476ms | Execution: 44.608ms | React with ❌ to remove this embed.
Ah okay this makes sense - is there any way of directly converting any data structure to bytes or will it be in its own format like bf?
For simple structs that only contain primitive types you can come up with a pure binary representation but once you start including references to other types that goes out the window.
For instance, a type that contains a field that is an array of strings: in memory that field is an address (a pointer) that points to an array. Every element of the array is itself a pointer, each of which points to a string instance. You can't really directly convert such a thing to a simple array of bytes because of the indirection caused by having pointers.
This is why we use serializers to convert complex types to some format that can be written to disk or sent over the network - often this is a textual format (think JSON) but binary formats are also possible (think ProtoBuf).
BinaryFormatter has its own format but it has huge security holes and is considered deprecated. Don't use it.
Sure thank you very much for the help - I'll look for alternatives to binary formatter