Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Convert from byte[] to int and int to byte[]
Message
De
05/01/2005 16:35:04
Cetin Basoz
Engineerica Inc.
Izmir, Turquie
 
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Divers
Thread ID:
00974405
Message ID:
00974522
Vues:
18
This message has been marked as a message which has helped to the initial question of the thread.
>Is there an easy way to convert from a byte array to integer? Is there an equaly easy way to convert from integer to a byte array?
>
>Currently what I do for a byte array of length 2:
>
>System.Int32 iValue = 42000;
>System.Byte[] bValue = new System.Byte[2];
>
>bValue[0] = Convert.ToByte(iValue/256);
>bValue[1] = Convert.ToByte(iValue%256);
>
>System.Int32 iRetVal;
>iRetVal = Convert.ToInt32(Convert.ToInt32(bValue[0]) * 256 + Convert.ToInt32(bValue[1]));
>
>
>Now this isn't a lot of work for byte[2] but it will get kinda messy for byte[4]. I have got it working for byte[4], but I was wondering if there was a simpler/built in (one-liner) way of doing this.
>
>Any help would be appreciated.
>
>Thanks,
>Einar

Einar,
Use BitConverter class as Zakaria pointed:
using System;
class quickTest
{
   static void Main() {

   System.Int64 paraInt64 = 4294967295;
   System.Int32 iValue = 42000;
   
   System.Byte[] bValue1 = BitConverter.GetBytes(iValue);
   System.Byte[] bValue2 = BitConverter.GetBytes(paraInt64);

   Console.WriteLine("Int sizes {0} and {1}",bValue1.Length,bValue2.Length);

   int iRetVal1 = BitConverter.ToInt32(bValue1,0);
   long iRetVal2 = BitConverter.ToInt64(bValue2,0);

   Console.WriteLine("Values back: {0} and {1}",iRetVal1,iRetVal2);
}}
Cetin
Çetin Basöz

The way to Go
Flutter - For mobile, web and desktop.
World's most advanced open source relational database.
.Net for foxheads - Blog (main)
FoxSharp - Blog (mirror)
Welcome to FoxyClasses

LinqPad - C#,VB,F#,SQL,eSQL ... scratchpad
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform