How to always take the next 2 elements of a string

Asked

Viewed 31 times

-3

I have the following string: gxAjaxKey = "FF00FFFFFFFF2426FFFFFF046448FF70"

I must take 2 elements at a time from this string and convert to byte:

FF = 255

00 = 0

FF = 255

.

.

.

70 = 112

I wrote the following code :

int GxAjaxKeyLength = gxAjaxKey.Length;

for(int i=0; i < GxAjaxKeyLength; i += 2)
{
    var a = gxAjaxKey.Substring(i, i + 2);
    mainArray[(i/2)] = Convert.ToByte(a, 16);
}

The problem is that in the second interaction, instead of getting 00 I’m getting 00FF. I’m not seeing where my mistake is.

1 answer

2


The second substring parameter is the amount of characters you want to pull from the string from the index i. So in the second iteration of the loop it pulls from 2 to 6 (2 + 4).

To fix you can use

var substring = key.Substring(i, 2);

Complete code:

String key = "FF00FFFFFFFF2426FFFFFF046448FF70";
int KEY_LENGTH = key.Length;

for(int i=0; i < KEY_LENGTH; i += 2)
{
  String substring = key.Substring(i, 2);
  mainArray[(i/2)] = Convert.ToByte(substring, 16);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.