Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Convert Integer to Byte Array in C#
WhatsApp
Mahesh Chand
6y
220.2k
0
2
100
Article
The BitConverter class in .NET Framework is provides functionality to convert base data types to an array of bytes, and an array of bytes to base data types.
The BitConverter class has a static overloaded GetBytes method that takes an integer, double or other base type value and convert that to a array of bytes. The BitConverter class also have other static methods to reverse this conversion. Some of these methods are ToDouble, ToChart, ToBoolean, ToInt16, and ToSingle.
The following code snippet converts different integer values to a byte array and vice-versa.
namespace
BitConverterSample
{
class
Program
{
static
void
Main(
string
[] args)
{
Console.WriteLine(
"Int and byte arrays conversion sample."
);
// Create double to a byte array
Int32 i32 = 125;
Console.WriteLine(
"Int value: "
+ i32.ToString());
byte
[] bytes = ConvertInt32ToByteArray(i32);
Console.WriteLine(
"Byte array value:"
);
Console.WriteLine(BitConverter.ToString(bytes));
Console.WriteLine(
"Byte array back to Int32:"
);
// Create byte array to Int32
double
dValue = ConvertByteArrayToInt32(bytes);
Console.WriteLine(dValue.ToString());
Console.ReadLine();
}
public
static
byte
[] ConvertInt32ToByteArray(Int32 I32)
{
return
BitConverter.GetBytes(I32);
}
public
static
byte
[] ConvertIntToByteArray(Int16 I16)
{
return
BitConverter.GetBytes(I16);
}
public
static
byte
[] ConvertIntToByteArray(Int64 I64)
{
return
BitConverter.GetBytes(I64);
}
public
static
byte
[] ConvertIntToByteArray(
int
I)
{
return
BitConverter.GetBytes(I);
}
public
static
double
ConvertByteArrayToInt32(
byte
[] b)
{
return
BitConverter.ToInt32(b, 0);
}
}
}
BitConverter
C#
convert byte array to int
int32
int64
integer
Up Next
Ebook Download
View all
Programming Dictionary in C#
Read by 29k people
Download Now!
Learn
View all
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.
Membership not found