tags:

views:

133

answers:

2

Hi fellow programmers,

I am not used to manipulate bytes in my code and I have this piece of code that is written in Java and I would need to convert it to its C# equivalent :

protected static final int putLong(final byte[] b, final int off, final long val) {
    b[off + 7] = (byte) (val >>> 0);
    b[off + 6] = (byte) (val >>> 8);
    b[off + 5] = (byte) (val >>> 16);
    b[off + 4] = (byte) (val >>> 24);
    b[off + 3] = (byte) (val >>> 32);
    b[off + 2] = (byte) (val >>> 40);
    b[off + 1] = (byte) (val >>> 48);
    b[off + 0] = (byte) (val >>> 56);
    return off + 8;
}

Thanks in advance for all your help, I am looking forward to learn from this.

I would also appreciate to know if there is a C# equivalent to the Java function :

Double.doubleToLongBits(val);

edit : found the answer to my second question : BitConverter.DoubleToInt64Bits

+4  A: 
  1. You can't have final parameters in C#
  2. Methods are "final" by default.
  3. There is no unsigned shift right in C#

So we get:

protected static int putLong(byte [] b, int off, long val) {
    b[off + 7] = (byte) (val >> 0);
    b[off + 6] = (byte) (val >> 8);
    b[off + 5] = (byte) (val >> 16);
    b[off + 4] = (byte) (val >> 24);
    b[off + 3] = (byte) (val >> 32);
    b[off + 2] = (byte) (val >> 40);
    b[off + 1] = (byte) (val >> 48);
    b[off + 0] = (byte) (val >> 56);
    return off + 8;
}

For more information on C# bitwise shift operators: http://www.blackwasp.co.uk/CSharpShiftOperators.aspx

Corey Sunwold
doesn't byte == byte?
Keith Nicholas
@Keith Nicholas Doh! Of course. Fixed.
Corey Sunwold
Thank you sir for the clear answer! Any equivalent for the java method Double.doubleToLongBits(val); ?
ibiza
Also keep in mind that since 'byte' is unsigned in C# as opposed to signed in Java, that's the reason there's no real need for an unsigned byte shift operator in C#. (All signed integers have unsigned equivalents.)
nonoitall
@ibiza I'm not sure. You should try opening another question for that.
Corey Sunwold
A: 

pretty much take out the final, and change the >>> to >>

Keith Nicholas