|
-
March 14th, 2006, 02:39 AM
#1
get an Int from a byte array
Hello,
is there an easy way as in C or c++ to get an integer from a byte array
c code
Code:
char test[4];
return (int)test;
Regards
Hansjörg
-
March 14th, 2006, 02:54 AM
#2
Re: get an Int from a byte array
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
}
}
}
-
March 14th, 2006, 02:54 AM
#3
Re: get an Int from a byte array
You say Byte array, but your example has char array...
But if you mean byte[] you could use the System.BitConverter.ToInt32() method.
/Leyan
-
March 14th, 2006, 03:03 AM
#4
Re: get an Int from a byte array
the second hint is great. It was really that what I needed.
Shame on me for c code....
Regards
Hansjörg
-
March 14th, 2006, 03:09 AM
#5
Re: get an Int from a byte array
Is it also possible to convert the data to bigEndian?
-
March 15th, 2006, 08:40 AM
#6
Re: get an Int from a byte array
look for Encoding class, hansipet!
If you think you CAN, you can, If you think you CAN'T, you are probably right.
Have some nice Idea to share? Write an Article Online or Email to us and You may WIN a Technical Book from CG.
-
March 15th, 2006, 02:27 PM
#7
Re: get an Int from a byte array
do some shifting to turn littleendian to bigendian :P
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|