Hello,
is there an easy way as in C or c++ to get an integer from a byte array
c code
RegardsCode:char test[4];
return (int)test;
Hansjörg
Printable View
Hello,
is there an easy way as in C or c++ to get an integer from a byte array
c code
RegardsCode:char test[4];
return (int)test;
Hansjörg
First, C++ code is not correct, because it converts pointer to int. I would do this with union in C++.
C# contains FieldOffset attribute which allows to get the same functionality as C++ union.
Code:using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
[StructLayout( LayoutKind.Explicit)]
struct MyUnion
{
[FieldOffset(0)] public byte byte1;
[FieldOffset(1)] public byte byte2;
[FieldOffset(2)] public byte byte3;
[FieldOffset(3)] public byte byte4;
[FieldOffset(0)] public int myInt;
};
class Program
{
static void Main(string[] args)
{
MyUnion u;
u.myInt = 0; // prevent compiler error
u.byte1 = 0;
u.byte2 = 1;
u.byte3 = 0;
u.byte4 = 0;
Console.WriteLine(u.myInt); // result is 256 - Litle Endian machine
}
}
}
You say Byte array, but your example has char array...
But if you mean byte[] you could use the System.BitConverter.ToInt32() method.
/Leyan
the second hint is great. It was really that what I needed.
Shame on me for c code....
Regards
Hansjörg
Is it also possible to convert the data to bigEndian?
look for Encoding class, hansipet!
do some shifting to turn littleendian to bigendian :P