Big Endian Format

M

Matt

I receive a file from a client and the first 8 bytes are in Big Endian
format to denote the length of the following data. This is one of the
security requirements. I also have to do the same thing when sending a
response file back to them. Does anyone know an easy way to convert this
Big Endian format from/to an integer easily to make it easy to work with?

Thanks,

Matt
 
J

Joerg Jooss

Matt said:
I receive a file from a client and the first 8 bytes are in Big
Endian format to denote the length of the following data. This is
one of the security requirements. I also have to do the same thing
when sending a response file back to them. Does anyone know an easy
way to convert this Big Endian format from/to an integer easily to
make it easy to work with?

I guess you can use IPAddress.NetworkToHostOrder() here.

Cheers,
 
J

Jon Skeet [C# MVP]

Matt said:
I receive a file from a client and the first 8 bytes are in Big Endian
format to denote the length of the following data. This is one of the
security requirements. I also have to do the same thing when sending a
response file back to them. Does anyone know an easy way to convert this
Big Endian format from/to an integer easily to make it easy to work with?

I have some classes to help with this kind of thing in my miscellaneous
utilities library.

See http://www.pobox.com/~skeet/csharp/miscutil
 
L

Leslie Sanford

Matt said:
I receive a file from a client and the first 8 bytes are in Big Endian
format to denote the length of the following data. This is one of the
security requirements. I also have to do the same thing when sending
a response file back to them. Does anyone know an easy way to convert
this Big Endian format from/to an integer easily to make it easy to
work with?

You could store the bytes in an array and convert them with the
BitConverter class. If the bytes are sent from the MSB to LSB, you could
store them in the array starting at Length - 1 index (7th, in this
case). Since you know the size of the array beforehand, this shouldn't
be hard. Once you have the array filled, you can convert it to an ulong
or long (seeing that it's an 8 byte number) using the appropriate method
in the BitConverter class.

When you're ready to send the length back, you can call
BitConverter.GetBytes to get a byte array representing the number.
Reverse the array with Array.Reverse, or start at the end of the array
(Length - 1) and work your way through the array sending the bytes.

I'm fairly certain this will work, but would appreciate any corrections
if I'm mistaken about something.
 
M

Matt

Thanks to everyone that responded to this, I believe I have found a solution
based on your recommendations. ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top