Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between C# byte format

I’m trying to download some bytes over my xampp server to use it inside my C# program, but there is a difference between the length of the bytes as shown here :

        WebClient wc = new WebClient();
        byte[] bytesweb = wc.DownloadData(@"http://127.0.0.1/test.txt");

        int lenweb = bytesweb.Length; //The value of lenweb is 69
        

And then when I use the same bytes directly inside the program as shown here :

        byte[] bytesapp = new byte[] { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

        int lenapp = bytesapp.Length; //The value of lenapp is 11

So I can’t understand what changed between thoses 2, what to do so the length value is equal to "11" while importing it using my server

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

nb : the value of "test.txt" is : { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

>Solution :

nb : the value of "test.txt" is : { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

So, your file contains the literal text { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };.

This is a 69-byte text which, when interpreted as a C# code snippet, represents a 11-byte byte array. This explains the difference you see.


How do you fix this? Don’t store your byte arrays as text, store them as a bytes:

byte[] bytesapp = new byte[] { 0x00, 0x00, 0x40, 0x00, 0x00, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x40 };

// This creates the file you want to put on your web server.
File.WriteAllBytes(@"C:\temp\test.bin", bytesapp);

(Alternatively, you could write code that parses your text file and converts it to a "real" byte array. This question contains example code that can do this for you if you store your data in the following format: 0000400000e81000000040.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading