galets
galets

Reputation: 18482

Cast int to byte[4] in .NET

I was wondering if anyone here knows an efficient way to cast an integer to a byte[4]? I'm trying to write an int into MemoryStream, and this thing wants me to give it bytes

Upvotes: 4

Views: 683

Answers (5)

Quintin Robinson
Quintin Robinson

Reputation: 82345

You could also do your own shifting! Although i'd use the built in methods figured i'd throw this out there for fun.

byte[] getBytesFromInt(int i){
    return new byte[]{
        (byte)i,
        (byte)(i >> 8),
        (byte)(i >> 16),
        (byte)(i >> 24)
    };
}

Of course then you have to worry about endian.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500865

  • BinaryWriter will be the simplest solution to write to a stream
  • BitConverter.GetBytes is most appropriate if you really want an array
  • My own versions in MiscUtil (EndianBitConverter and EndianBinaryWriter) give you more control over the endianness, and also allow you to convert directly into an existing array.

Upvotes: 6

Greg Beech
Greg Beech

Reputation: 136647

You can use BitConverter.GetBytes if you want to convert a primitive type to its byte representation. Just remember to make sure the endianness is correct for your scenario.

Upvotes: 14

Daniel LeCheminant
Daniel LeCheminant

Reputation: 51081

Use a BinaryWriter (constructed with your memory stream); it has a write method that takes an Int32.

BinaryWriter bw = new BinaryWriter(someStream);
bw.Write(intValue);
bw.Write((Int32)1);
// ...

Upvotes: 7

Related Questions