Link to home
Start Free TrialLog in
Avatar of BlearyEye
BlearyEyeFlag for United States of America

asked on

Converting long to byte array and back

I need to convert a long to a byte array and back again. I can't use BitConverter since the Micro Framework version of C# doesn't support it. Here's the code I'm using:
            long origLong = long.MinValue;
            byte[] bytes = new byte[8];
            for (int i = 0; i < 8; i++) {
                bytes[i] = (byte)(origLong >> (i * 8) & 0xFF);
            }
            long newLong = 0;
            for (int i = 0; i < 8; i++) {
                newLong = newLong | (long)(bytes[i] << (i * 8));
            }
            for (int i = 0; i < bytes.Length; i++) {
                Debug.Write(bytes[i] + " ");
            }
            Debug.Print("");
            Debug.Print("orig: " + origLong + ", new: " + newLong);

Open in new window

The results in the Output are:
0 0 0 0 0 0 0 128 
orig: -9223372036854775808, new: -2147483648

Open in new window

It looks like the conversion to a byte array is good but the conversion back to long is not. Also, on the statement with the OR operator (#8), I get the warning "Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first".

How can I do this?
ASKER CERTIFIED SOLUTION
Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of BlearyEye

ASKER

Perfect, thanks.
As a follow-up, I've come across two implementations of BitConverter for MF:

https://bitbucket.org/aalmada/hydramf/src/779d1c524a9c/HydraMF.Hardware/BitConverter.cs
http://forums.netduino.com/index.php?/topic/308-bitconverter/, and accompanying comments (there are bugs in the posted code).
Thanks, interesting!