converting a byte array to an integer

G

Guest

Hello Everyone,

How can I convert an array of bytes to an integer so for example, I have
this

a[0]= "00001010"
a[1]="11111111"
a[2]="01110011"

How can I convert this to an integer in .net

Thanks
 
G

Guest

Vinki said:
How can I convert an array of bytes to an integer so for example, I have
this

a[0]= "00001010"
a[1]="11111111"
a[2]="01110011"

How can I convert this to an integer in .net

If you indeed have byte[] then you can use BitConverter.ToInt32.

If you have strings in binary radix you will need some decoding.

Snippet:


private static string DIGITS = "0123456789ABCDEF";
private static int FromAny(string s, int radix)
{
int res = 0;
char[] sa = s.ToCharArray();
for (int i = 0; i < s.Length; i++) {
res = res * radix + DIGITS.IndexOf(sa);
}
return res;
}
public static int FromBin(string s)
{
return FromAny(s, 2);
}

Arne
 
M

Michael C

Vinki said:
Hello Everyone,

How can I convert an array of bytes to an integer so for example, I have
this

a[0]= "00001010"
a[1]="11111111"
a[2]="01110011"

How can I convert this to an integer in .net

This is an array of strings, not bytes. It's pretty easy to convert though:

you can use something like this function below or just use
Convert.ToInt32(a[0], 2)

private static int BinaryStringToInt(string Value)
{
int ret = 0;
for(int i = 0; i < Value.Length; i++)
{
ret <<= 1;
if(Value.Substring(i, 1) == "1") ret++;
}
return ret;
}
 
K

KWienhold

Hello Everyone,

How can I convert an array of bytes to an integer so for example, I have
this

a[0]= "00001010"
a[1]="11111111"
a[2]="01110011"

How can I convert this to an integer in .net

Thanks

As these are binary strings, I'd simply use
Convert.ToInt32("00001010", 2).

hth,
Kevin Wienhold
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top