11

I am trying to do some conversion in C#, and I am not sure how to do this:

private int byteArray2Int(byte[] bytes)
{
    // bytes = new byte[] {0x01, 0x03, 0x04};

    // how to convert this byte array to an int?

    return BitConverter.ToInt32(bytes, 0); // is this correct? 
    // because if I have a bytes = new byte [] {0x32} => I got an exception
}

private string byteArray2String(byte[] bytes)
{
   return System.Text.ASCIIEncoding.ASCII.GetString(bytes);

   // but then I got a problem that if a byte is 0x00, it show 0x20
}

Could anyone give me some ideas?

halfer
  • 19,824
  • 17
  • 99
  • 186
olidev
  • 20,058
  • 51
  • 133
  • 197

4 Answers4

28

BitConverter is the correct approach.

Your problem is because you only provided 8 bits when you promised 32. Try instead a valid 32-bit number in the array, such as new byte[] { 0x32, 0, 0, 0 }.

If you want an arbitrary length array converted, you can implement this yourself:

ulong ConvertLittleEndian(byte[] array)
{
    int pos = 0;
    ulong result = 0;
    foreach (byte by in array) {
        result |= ((ulong)by) << pos;
        pos += 8;
    }
    return result;
}

It's not clear what the second part of your question (involving strings) is supposed to produce, but I guess you want hex digits? BitConverter can help with that too, as described in an earlier question.

Community
  • 1
  • 1
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • a list of bytes is fine as I declared as above I think – olidev May 29 '11 at 00:19
  • 1
    `foreach` in byte conversion look really insane( – Mikant May 29 '11 at 00:34
  • @Mikant: Can you explain what you think the problem is? It works for me: http://ideone.com/ML8Nb – Ben Voigt May 29 '11 at 00:38
  • 1
    usually we use such a type of conversion to gain speed... not to worry about the environment we work in. `foreach` sugar may slow the `work` up to hundreds of times... i just want to say that usage of the `foreach` keyword 'must' be consciously recognized – Mikant May 29 '11 at 00:56
  • @Mikant: I think you're confusing this with some other case. `foreach` on arrays is very fast. If there were a generic interface here, such as `IEnumerable`, there could be performance problems. But the code I show has no "hundreds of times" overhead. You could probably squeeze out a few more percent by unrolling, but that's all. – Ben Voigt May 29 '11 at 01:05
  • How can I go back from ulong to my own bytes array? – HMagdy May 27 '14 at 15:24
  • This function you suggested gives warning: warning CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first. Why? –  Oct 15 '15 at 07:20
3
byte[] bytes = { 0, 0, 0, 25 };

// If the system architecture is little-endian (that is, little end first), 
// reverse the byte array. 
if (BitConverter.IsLittleEndian)
  Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
josliber
  • 43,891
  • 12
  • 98
  • 133
Barak Rosenfeld
  • 307
  • 1
  • 6
  • 14
1

A fast and simple way of doing this is just to copy the bytes to an integer using Buffer.BlockCopy:

UInt32[] pos = new UInt32[1];
byte[] stack = ...
Buffer.BlockCopy(stack, 0, pos, 0, 4);

This has the added benefit of being able to parse numerous integers into an array just by manipulating offsets..

JGU
  • 879
  • 12
  • 14
1
  1. this is correct, but you're missing, that Convert.ToInt32 'wants' 32 bits (32/8 = 4 bytes) of information to make a conversion, so you cannot convert just One byte: `new byte [] {0x32}

  2. absolutely the the same trouble you have. and do not forget about the encoding you use: from encoding to encoding you have 'different byte count per symbol'

Mikant
  • 299
  • 3
  • 18
  • 1 is OK. question 2 is not clear for me, so which encoding format should I use? thanks in advance – olidev May 29 '11 at 00:41