Twitter iPhone pliant OnePlus 11 PS5 Disney+ Orange Livebox Windows 11

byte[] en hexa

5 réponses
Avatar
Fab
Bonjour,

Je souhaite transformer un tableau de byte (byte[]) en hexadecimal (string)
Et inversement une chaine hexa en byte[]

J'ai une fonction :
public static string byteToHexaString(byte[] tableau)
{
string chaine_retour = "";
for (int i=0; i<tableau.Length; i++)
{
chaine_retour += Convert.ToString(tableau[i],16);
}
return chaine_retour;
}

Mais cette fonction ne semble pas bien fonctionner pour tous les cas. Alors
que dans certains cas elle devrait me donner
"0e67d6c94adc79745e462602a23cdfa3", elle me donne
"e67d6c94adc79745e462602a23cdfa3", c'est à dire qu'elle retire le "0" du
début !

Pouvez-vous me donner une autre manière de faire ou une explication à mon
problème.

Merci d'avance.

Fabrice

5 réponses

Avatar
Tsunoo Rhilty
> "0e67d6c94adc79745e462602a23cdfa3", elle me donne
"e67d6c94adc79745e462602a23cdfa3", c'est à dire qu'elle retire le "0" du
début !



effectivement car le chiffre 14 devient 0xe et non 0x0e.
Tu peux avec la fonction string.format obtenir les 0 qui te manquent (mais
là je n'ai pas la syntaxe sous la main (en C %02d) ).

...pris sur le net...

StringOut=StringOut + String.Format("{0:X2} ",InByte);
Avatar
Tsunoo Rhilty
meilleure syntaxe (pris sur le net)

//converter hex string to byte and byte to hex string
public static string ByteToString(byte[] InBytes)
{
string StringOut="";
foreach (byte InByte in InBytes)
{
StringOut=StringOut + String.Format("{0:X2} ",InByte);
}
return StringOut;
Avatar
Tsunoo Rhilty
> Et inversement une chaine hexa en byte[]



voila le code:


public static byte[] StringToByte(string InString)
{
string[] ByteStrings;
ByteStrings = InString.Split(" ".ToCharArray());
byte[] ByteOut;
ByteOut = new byte[ByteStrings.Length-1];
for (int i = 0;i==ByteStrings.Length-1;i++)
{
ByteOut[i] = Convert.ToByte(("0x" + ByteStrings[i]));
}
return ByteOut;
}
}
}
Avatar
Fab
Merci, je viens de trouver comment régler mon souci.
J'utilise :
return BitConverter.ToString(tableauDeByte).Replace("-",string.Empty);

A+

Fabrice

"Tsunoo Rhilty" a écrit :

meilleure syntaxe (pris sur le net)

//converter hex string to byte and byte to hex string
public static string ByteToString(byte[] InBytes)
{
string StringOut="";
foreach (byte InByte in InBytes)
{
StringOut=StringOut + String.Format("{0:X2} ",InByte);
}
return StringOut;





Avatar
Michel Foucault
> Ce message est au format MIME. Comme votre programme de lecture de courriers ne comprend pas


ce format, il se peut que tout ou une partie de ce message soit illisible.

--B_3227685502_456752
Content-type: text/plain;
charset="ISO-8859-1"
Content-transfer-encoding: 8bit

Je trouve les méthode proposée trop coûteuses (en temps et en mémoire) du a
l'utilisation de l'opérateur '+' avec les string et l'utilisation de
string.Replace explose lorsque les données sont trop grosses (> 1Mo)

Il est préférable d'utiliser la classe StringBuilder, et d'effectuer un
string.Replace sur des données plus petite (la méthode ToHexaString est
accompagnée d¹une méthode auxiliaire qui fait le travail.

Je n'ai pas trouvé un moyen de se passer de du string.Replace qui est aussi
coûteux qu¹inutile si la fonction formatait correctement la chaîne hexa sans
les '-'.

Je pense que la méthode FromHexaString peux également être optimisée mais je
n'ai pas trouvé mieux que ce qui était proposé (elle est 2 fois plus
coûteuse en temps que ToHexaString)


Voici le code accompagné d¹un test :

public class Program
{
    static string ToHexaString(byte[] data, int offset, int length)
    {
        return BitConverter.ToString(data, offset, length).Replace("-",
string.Empty);
    }
    public static string ToHexaString(byte[] data)
    {
        StringBuilder ret = new StringBuilder(data.Length << 1);
        int chunck = 1 << 10;
        int left = data.Length;
        int offset = 0;
        while (left > 0)
        {
            int length = Math.Min(chunck, left);
            ret.Append(ToHexaString(data, offset, length));
            offset += length;
            left -= length;
        }
        return ret.ToString ();
    }

    public static byte[] FromHexaString(string data)
    {
        int nb = data.Length / 2;
        byte[] ret = new byte[nb];
        for (int i = 0; i < nb; i++)
        {
            string str = data.Substring(i << 1, 2);
            ret[i] = Convert.ToByte(str, 16);
        }
        return ret;
    }

    public static void Main()
    {
        DateTime start = DateTime.Now;
        int size = 10 << 20;
        TimeSpan dt = DateTime.Now - start; byte[] data = new byte[size];

        Console.WriteLine("{0:0.00} Mo of random data", data.Length /
(double)(1 << 20));

        Random r = new Random();

        start = DateTime.Now;
        r.NextBytes(data);
        dt = DateTime.Now - start;
        Console.WriteLine(string.Format("NextBytes : {0:0.00}s",
dt.TotalMilliseconds / 1000.0));

        start = DateTime.Now;
        string str1 = ToHexaString(data);
        dt = DateTime.Now - start;
        Console.WriteLine(string.Format("ToHexa : {0:0.00}s",
dt.TotalMilliseconds / 1000.0 ));

        start = DateTime.Now;
        data = FromHexaString(str1);
        dt = DateTime.Now - start;
        Console.WriteLine(string.Format("FromHexa : {0:0.00}s",
dt.TotalMilliseconds / 1000.0));

        string str2 = ToHexaString(data);


        Console.WriteLine(string.Format("{0}...{1}", str1.Substring(0, 10),
str1.Substring(str1.Length - 1 - 10)));
        Console.WriteLine(string.Format("{0}...{1}", str2.Substring(0, 10),
str2.Substring(str2.Length - 1 - 10)));
        Console.WriteLine("equals : " + (str1 == str2));
    }
}


Le 11/04/06 15:40, dans e1gbi0$1bu$, « Tsunoo Rhilty »
a écrit :


Et inversement une chaine hexa en byte[]



voila le code:


public static byte[] StringToByte(string InString)
{
string[] ByteStrings;
ByteStrings = InString.Split(" ".ToCharArray());
byte[] ByteOut;
ByteOut = new byte[ByteStrings.Length-1];
for (int i = 0;i==ByteStrings.Length-1;i++)
{
ByteOut[i] = Convert.ToByte(("0x" + ByteStrings[i]));
}
return ByteOut;
}
}
}






--B_3227685502_456752
Content-type: text/html;
charset="ISO-8859-1"
Content-transfer-encoding: quoted-printable

<HTML>
<HEAD>
<TITLE>Re: byte[] en hexa</TITLE>
</HEAD>
<BODY>
<FONT FACE="Verdana, Helvetica, Arial"><SPAN STYLE='font-size:12.0px'>Je tr ouve les m&eacute;thode propos&eacute;e trop co&ucirc;teuses (en temps et en m&eacute;moire) du a l'utilisation de l'op&eacute;rateur '+' avec les strin g et l'utilisation de string.Replace explose lorsque les donn&eacute;es sont trop grosses (&gt; 1Mo)<BR>
<BR>
Il est pr&eacute;f&eacute;rable d'utiliser la classe StringBuilder, et d'ef fectuer un string.Replace sur des donn&eacute;es plus petite (la m&eacute;th ode ToHexaString est accompagn&eacute;e d&#8217;une m&eacute;thode auxiliair e qui fait le travail.<BR>
<BR>
Je n'ai pas trouv&eacute; un moyen de se passer de du string.Replace qui es t aussi co&ucirc;teux qu&#8217;inutile si la fonction formatait correctement la cha&icirc;ne hexa sans les '-'.<BR>
<BR>
Je pense que la m&eacute;thode FromHexaString peux &eacute;galement &ecirc; tre optimis&eacute;e mais je n'ai pas trouv&eacute; mieux que ce qui &eacute ;tait propos&eacute; (elle est 2 fois plus co&ucirc;teuse en temps que ToHex aString)<BR>
<BR>
<BR>
Voici le code accompagn&eacute; d&#8217;un test :<BR>
<BR>
public class Program<BR>
{<BR>
    static string ToHexaString(byte[] data, int offset, int length)<BR>
    {<BR>
        return BitConverter.ToString(data, offset, length).Replace(&quot;-& quot;, string.Empty);<BR>
    }<BR>
    public static string ToHexaString(byte[] data) <BR>
    {<BR>
        StringBuilder ret = new StringBuilder(data.Length &lt;&lt; 1);<BR>
        int chunck = 1 &lt;&lt; 10;<BR>
        int left = data.Length;<BR>
        int offset = 0;<BR>
        while (left &gt; 0)<BR>
        { <BR>
            int length = Math.Min(chunck, left);<BR>
            ret.Append(ToHexaString(data, offset, length));<BR>
            offset += length;<BR>
            left -= length;<BR>
        }<BR>
        return ret.ToString ();<BR>
    } <BR>
<BR>
    public static byte[] FromHexaString(string data)<BR>
    {<BR>
        int nb = data.Length / 2;<BR>
        byte[] ret = new byte[nb];<BR>
        for (int i = 0; i &lt; nb; i++)<BR>
        {<BR>
            string str = &nbsp;data.Substring(i &lt;&lt; 1, 2);<BR>
            ret[i] = Convert.ToByte(str, 16);<BR>
        }<BR>
        return ret;<BR>
    } <BR>
<BR>
    public static void Main()<BR>
    {<BR>
        DateTime start = DateTime.Now;<BR>
        int size = 10 &lt;&lt; 20;<BR>
        TimeSpan dt = DateTime.Now - start; byte[] data = new byte[size]; < BR>
<BR>
        Console.WriteLine(&quot;{0:0.00} Mo of random data&quot;, data.Leng th / (double)(1 &lt;&lt; 20)); <BR>
<BR>
        Random r = new Random(); <BR>
<BR>
        start = DateTime.Now;<BR>
        r.NextBytes(data);<BR>
        dt = DateTime.Now - start;<BR>
        Console.WriteLine(string.Format(&quot;NextBytes : {0:0.00}s&quot;, dt.TotalMilliseconds / 1000.0)); <BR>
<BR>
        start = DateTime.Now;<BR>
        string str1 = ToHexaString(data);<BR>
        dt = DateTime.Now - start;<BR>
        Console.WriteLine(string.Format(&quot;ToHexa : {0:0.00}s&quot;, dt. TotalMilliseconds / 1000.0 )); <BR>
<BR>
        start = DateTime.Now;<BR>
        data = FromHexaString(str1);<BR>
        dt = DateTime.Now - start;<BR>
        Console.WriteLine(string.Format(&quot;FromHexa : {0:0.00}s&quot;, d t.TotalMilliseconds / 1000.0)); &nbsp;<BR>
<BR>
        string str2 = ToHexaString(data); <BR>
<BR>
<BR>
        Console.WriteLine(string.Format(&quot;{0}...{1}&quot;, str1.Substri ng(0, 10), str1.Substring(str1.Length - 1 - 10)));<BR>
        Console.WriteLine(string.Format(&quot;{0}...{1}&quot;, str2.Substri ng(0, 10), &nbsp;str2.Substring(str2.Length - 1 - 10)));<BR>
        Console.WriteLine(&quot;equals : &quot; + (str1 == str2));<BR>
    }<BR>
}<BR>
<BR>
<BR>
Le 11/04/06 15:40, dans e1gbi0$1bu$, &laquo; Tsunoo Rhi lty &raquo; &lt;&gt; a &eacute;crit :<BR>
<BR>
<FONT COLOR="#0000FF">&gt; <BR>
</FONT><FONT COLOR="#008000">&gt;&gt; Et inversement une chaine hexa en byt e[]<BR>
</FONT><FONT COLOR="#0000FF">&gt; <BR>
&gt; voila le code:<BR>
&gt; <BR>
&gt; <BR>
&gt; public static byte[] StringToByte(string InString)<BR>
&gt; {<BR>
&gt; string[] ByteStrings;<BR>
&gt; ByteStrings = InString.Split(&quot; &quot;.ToCharArray());<BR>
&gt; byte[] ByteOut;<BR>
&gt; ByteOut = new byte[ByteStrings.Length-1];<BR>
&gt; for (int i = 0;i==ByteStrings.Length-1;i++)<BR>
&gt; {<BR>
&gt; ByteOut[i] = Convert.ToByte((&quot;0x&quot; + ByteStrings[i]));<BR>
&gt; }<BR>
&gt; return ByteOut;<BR>
&gt; }<BR>
&gt; }<BR>
&gt; } <BR>
&gt; <BR>
&gt; <BR>
</FONT></SPAN></FONT>
</BODY>
</HTML>


--B_3227685502_456752--