user1965804
user1965804

Reputation: 111

String to Hex int array?

Is it possible to convert a HEX string to an integer array?

// This string...
string a = "8FCC44";

// Should look like this:
int[] b = {0x8f,0xcc,0x44};

But I don't have any idea how to do this.

I found this question, but i can't understand the answer. I am new to C#, so it would be nice if anybody could give me an example.

Thanks in advance!

Upvotes: 2

Views: 1615

Answers (4)

Dave
Dave

Reputation: 8461

        static void Main(string[] args)
        {
            string a = "8fcc44";            
            int itemNumber = 0;
            int[] iArray = new int[3];
            for (int i = 0; i < a.Length - 1; i += 2)
            {
                iArray[itemNumber] = (int.Parse(a.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));
                itemNumber++;
            }
        }

Upvotes: 0

Magnus
Magnus

Reputation: 46977

Another way:

var a = "8fcc44";
var b = Enumerable.Range(0, a.Length / 2).Select(x => 
          Convert.ToInt32(a.Substring(x * 2, 2), 16)).ToArray();

Upvotes: 2

dotNET
dotNET

Reputation: 35430

int[] ConvertToIntArray(string a)
{
    List<int> x = new List<int>();
    for(int i=0; i<a.Length-1; i+=2)
        x.Add(int.Parse(a.Substring(i, 2), System.Globalization.NumberStyles.HexNumber));

    return x.ToArray();
}

You can then print them as Hex or Decimal using ToString() overloads of int (Int32) class.

Upvotes: 2

Carsten
Carsten

Reputation: 11636

The answer focuses on Java, but it is also possible to do this in C# in a similar way. Basicly you have to divide the string into substrings, each 2 characters long:

"8FCC44" -> "8F", "CC", "44"

You can do this using a for loop:

for (int i = 0; i < a.Length; i += 2)

The loop variable i represents the start index of the current substring, this is why it always increases by 2. We can convert each substring using Int32.Parse:

Convert.ToInt32(a.Substring(i, 2), 16);

The last parameter represents the base of the source string (HEX = base 16).

Now we need an array to store the results. The size of the array can be calculated by the length of the string, divided by the length of each substring (= 2):

int[] b = new int[a.Length / 2];

To bring it all together your code could look like this:

string a = "8FCC44";
int[] b = new int[a.Length / 2];

for (int i = 0, int j = 0; i < a.Length; i += 2, j++)
    b[j] = Convert.ToInt32(a.Substring(i, 2), 16);

Hope this helps!

Upvotes: 0

Related Questions