Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte array to int

Tags:

c#

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?

like image 231
olidev Avatar asked May 29 '11 00:05

olidev


People also ask

Can you convert a byte to an int?

A bytes object can be converted to an integer value easily using Python.

Can byte converted to int in Java?

The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int.

Can we convert byte array to file in Java?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.

How do you convert bytes to integers in python?

How to Convert Bytes to Signed Int in Python? To convert the bytes object to a signed int, we will set the parameter signed to True in the from_bytes() method.


2 Answers

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.

like image 181
Ben Voigt Avatar answered Oct 18 '22 00:10

Ben Voigt


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);
like image 21
Barak Rosenfeld Avatar answered Oct 18 '22 00:10

Barak Rosenfeld