1

I have the following line of Java code:

Float.intBitsToFloat(Integer.reverseBytes(dataInputStream.readInt()));

I want to do the same in C# and I have come up with the following code:

BitConverter.ToSingle(BitConverter.GetBytes(binaryReader.ReadInt32()), 0)

This code is incomplete because I can't find any equivalent to Java's Integer.reverseBytes-Method. How can I translate this into C#?

eddex
  • 1,622
  • 1
  • 15
  • 37
  • 1
    ^^ especially mind MarkusSchaber's comment on the answer: _" the IPAddress class has static Methods to convert between host and network byte orders"_ – Fildor Feb 27 '20 at 15:25
  • Thanks for the answer. I just read this question and according to this, Java stores Integers as Big Endian while C# uses Little Endian. Wouldn't that mean that my C# code is already correct since I reverse the bytes in Java? https://stackoverflow.com/questions/5952062/read-byte-array-from-c-sharp-that-is-written-from-java – eddex Feb 27 '20 at 15:30
  • Could be. You didn't include that in the question. But it's fairly easy to test that out, isn't it? – Fildor Feb 27 '20 at 15:31
  • Btw: If you are working on communication between the two, I'd recommend to use a common representation instead of binary. Like JSON for example. Or something more efficient. Unless you have a good reason not to, of course. It has an overhead but then again, you don't have to deal with this kind of stuff. – Fildor Feb 27 '20 at 15:33
  • If you're reading from a binary input, your best bet is probably to look at `BinaryPrimitives` - this has endian-specific read APIs, which means you can read it correctly in the endianness that you actually wanted – Marc Gravell Feb 27 '20 at 15:49
  • Unfortunately I can't change the format of the data. I tested what I mentioned in my previous comment and it is true. Because C# uses little endian by default I don't have to reverse the bytes and can simply use `binaryReader.ReadSingle();` – eddex Feb 27 '20 at 16:08

0 Answers0