Hi guys I need help how to convert my uint and int to 3 byte array. Converting it to 4 byte array is easy since .Net has BitConverter class but now I really need to convert it to 3 Byte Array hope someone can help me out. Thanks

Perhaps you could change this struct, so that it fits your 3 byte scheme:

struct IntBits
    {
        private int _bits;

        public IntBits(int InitialBitValue)
        {
            _bits = InitialBitValue;
        }

        //declare indexer
        public bool this[int index]
        {
            get
            {
                return (_bits & (1 << index)) != 0;
            }
            set
            {
                if (value)
                    _bits |= (1 << index);  //set bit index to 1
                else
                    _bits &= ~(1 << index); //set bit index to 0           
            }
        }
    }

Simple solution

int testVal = 1234;
byte[] data = System.BitConverter.GetBytes(testVal);
byte[] data2 = new byte[3];
data2[0] = data[0];
data2[1] = data[1];
data2[2] = data[2];

I am sure you have a reason for not wanting to do this though.
How about this then.

int testVal = 1234;
byte[] data = System.BitConverter.GetBytes(testVal);
byte[] data2 = new byte[3];
System.Buffer.BlockCopy(data, 0, data2, 0, 3);

A slightly cleverer alternative.

int testVal = 1234;
int[] data = new int[] { testVal };
byte[] data2 = new byte[3];
System.Buffer.BlockCopy(data, 0, data2, 0, 3);

technically endianess will really affect my problem anyway .net provided us the way to check it. I think ill test something using the OR and AND operator and should check if int value is > FFFFFF. Anyway guys thanks for sharing your thoughts, I will try it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.