-2

How can I convert array[1] to hexadecimal in C#

array[1] = 1443484

I have tried the following but it doesn't compile:

StringBuilder hex = new StringBuilder(array[1].Length * 2);

foreach (byte b in array[1])
  hex.AppendFormat("{0:x2}", b);

string value = hex.ToString();   
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
aishwarya
  • 1
  • 1
  • 2
    Possible duplicate of [Convert integer to hexadecimal and back again](https://stackoverflow.com/questions/1139957/convert-integer-to-hexadecimal-and-back-again) – Aleks Andreev Jul 05 '19 at 10:12
  • What is the desired outcome? – Dmitry Bychenko Jul 05 '19 at 10:12
  • `string value = Convert.ToString(array[1], 16);` and you'll have `"16069c"` – Dmitry Bychenko Jul 05 '19 at 10:13
  • 1
    What type is your `array` variable exactly? Your question is unclear and contradictory about it. You saying "_array[1]=1443484_" implies your `array` variable is an array of integers. But your code example, specifically `array[1].Length` and `foreach (byte b in array[1])`, implies that your `array` variable is a collection of byte arrays... So, what are we really dealing here with? –  Jul 05 '19 at 10:19
  • @DmitryBychenko Thanks.. I am getting error(can not convert from int to Iformat provider) for 16 using this solution – aishwarya Jul 05 '19 at 10:26
  • @aishwarya: Demo with `Convert.ToString(array[1], 16)` : https://dotnetfiddle.net/gE5B47 – Dmitry Bychenko Jul 05 '19 at 10:33

1 Answers1

1

If you want just to obtain hexadecimal representation, you can do it in one go:

 // 16069c
 string value = Convert.ToString(array[1], 16);

Or

 string value = array[1].ToString("x");

Or (padded version: at least 8 characters)

 // 0016069c
 string value = array[1].ToString("x8");

If you want to manipulate with bytes try BitConverter class

 byte[] bytes = BitConverter.GetBytes(array[1]);

 string value = string.Concat(bytes.Select(b => b.ToString("x2")));

Your code amended:

 using System.Runtime.InteropServices; // For Marshal

 ...

 // Marshal.SizeOf - length in bytes (we don't have int.Length in C#)
 StringBuilder hex = new StringBuilder(Marshal.SizeOf(array[1]) * 2);

 // BitConverter.GetBytes - byte[] representation
 foreach (byte b in BitConverter.GetBytes(array[1]))
   hex.AppendFormat("{0:x2}", b);

 // You can well get "9c061600" (reversed bytes) instead of "0016069c"
 // if BitConverter.IsLittleEndian == true 
 string value = hex.ToString(); 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215