简体   繁体   中英

C# Converting an int into an array of 2 bytes

I apologize in advance if my question is not clear enough, I don't have a lot of experience with c# and I encounter an odd problem. I am trying to convert an int into an array of two bytes (for example: take 2210 and get: 0x08, 0xA2), but all I'm getting is: 0x00, 0xA2, and I can't figure out why. Would highly appreciate any advice. (I've tried reading other questions regarding this matter, but couldn't find an helpful answer)

my code:

        profile_number = GetProfileName(); // it gets the int 
        profile_num[0] = (byte) ((profile_number & 0xFF00));
        profile_num[1] = (byte) ((profile_number & 0x00FF));
        profile_checksum = CalcProfileChecksum();

//Note: I'm referring to a 2-byte array, so the answer to the question regarding 4-byte arrays does not help me.

You need to shift the 1st byte:

 //profile_num[0] = (byte) ((profile_number & 0xFF00));
 profile_num[0] = (byte) ((profile_number & 0xFF00) >> 8);
 profile_num[1] = (byte) ((profile_number & 0x00FF));

First I thought that this is the simplest way:

public static byte[] IntToByteArray(int value)
{
    return (new BigInteger(value)).ToByteArray();
}

But i realised that ToByteArray returns only needed bytes. If the value is small (under 256) then a single byte will be returned. Another thing that I noticed is that values are reversed in the returned array so that the byte that is in the right (the most insignificant byte) is found in the left. So I come with a little revision:

public static byte[] IntToByteArrayUsingBigInteger(int value, int numberOfBytes)
    {
        var res = (new BigInteger(value)).ToByteArray().Reverse().ToArray();
        if (res.Length == numberOfBytes)
            return res;

        byte[] result = new byte[numberOfBytes];

        if (res.Length > numberOfBytes)
            Array.Copy(res, res.Length - numberOfBytes, result, 0, numberOfBytes);
        else
            Array.Copy(res, 0, result, numberOfBytes - res.Length, res.Length);

        return result;
    }

I know that this does not compare with the performance of having bitwise operations but for the sake of learning new things and if you prefeer to use high level classes that .NET provides instead of going low level and use bitwise operators i think it's a nice alternative.

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