简体   繁体   中英

Port C# Code to Java

Following problem: I have ac# program doing some de/encryption in a very low level way. I used a tool, to convert most of the c# code to Java, which worked for most of the things but when it comes to such low level parts, the tool fails. The following data structure is used inside:

[StructLayout(LayoutKind.Explicit)]
        private struct ByteUInt
        {
            [FieldOffset(0)]
            public byte Byte0;

            [FieldOffset(1)]
            public byte Byte1;

            [FieldOffset(2)]
            public byte Byte2;

            [FieldOffset(3)]
            public byte Byte3;

            [FieldOffset(0)]
            public uint FullUint;
        }

In the program, the bytes and the uint inside this struct are changed several times separately eg like this MyByteUint.Byte0 &= someByte; or MyMyteUint.FullUint = someByte & 0x0F or some other bitwise operations. Because the uint references the same memory as the 4 bytes, if i change one of them, the uint will change too and vice versa.

Since there are no real pointers in Java I don't know the best way to port such thing to Java, because i can not reference the memory directly. Is there any solution else than creating a class with getters and setters making fields private and updating the uint/bytes when changing the other values?

Thanks for your input.

I assume that the above struct is actually used to overlay (effectively) an array of bits as a byte array or an int array.

You can't do that in Java. Your choices are:

  • Model it as a byte array, and take the performance hit when you are doing indexed copying.
  • Model it as an int array, and use bit shifting and masking to do the byte-wise operations.
  • Use native code; ie code the encryption / decryption in C or C++ and use JNI or JNA or similar to call that code from Java.

You could also look at the IntBuffer or ByteBuffer classes. These are (IMO) unlikely improve performance for your encryption / decryption operations taken in isolation, but when you combine them with NIO I/O (as an alternative to old-school I/O + copying to / from arrays) you may get better performance.


But it is also worth pointing out that this all has the smell of premature optimization. I'd recommend writing the Java code the simplest way first, and worry about performance later .... if measurement tells you that it is a real concern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM