0

I'm working on a C# program to scrub extended ASCII characters (examples are in my input string) from a series of text files. Here's what I'm running into. While I can recast the char as Int32 in my for loop, I'm trying to see if there's any way, to re-cast the array as Int32 values? In a perfect world, I'd like to pass an Int32 array of rocessing methods directly. Right now, I'm planning on just creating a method that takes the char array and returns an Int32 array. Is there an easier way to do this that would be similar to the comment I've included in my code?

string value = "Slide™1½”C4®";
byte[] asciiValue = Encoding.ASCII.GetBytes(value);   // byte array
char[] array = value.ToCharArray();                   // char array
 /* 
    is there something like
       Int32[] int32Array = array[].ToInt32();
 */
Console.WriteLine("CHAR\tBYTE\tINT32"); 
for (int i = 0; i < array.Length; i++) {
    char  letter     = array[i];
    byte  byteValue  = asciiValue[i];
    Int32 int32Value = array[i];
     /* 
        ... evaluate int32Value and do stuff ...  
     */
    Console.WriteLine("{0}\t{1}\t{2}", letter, byteValue, int32Value);
}
Console.ReadLine();

My plan B:

private Int32[] RecastCharArray(char[] array)
{
    Int32[] int32Value ;
    for (int i = 0; i < array.Length; i++) {
         int32Value[i] = array[i];
    }
    return int32Value;
}
dwwilson66
  • 6,806
  • 27
  • 72
  • 117
  • why do you want a 32bit value for the ascii character? – fast Apr 22 '14 at 15:48
  • See http://stackoverflow.com/questions/23224360/why-are-ascii-values-of-a-byte-different-when-cast-as-int32. I need to be able to differentiate the four different characters that are showing up with a byte value of 63. – dwwilson66 Apr 22 '14 at 15:54

3 Answers3

2

You can use LINQ.

char[] array = new char[] { 'a', 'b', 'c', '1', '2', '3' };
int[] int32Value = array.Select(r=> (int) r).ToArray();

If you want to convert numeric characters to int like changing character '1' to digit 1 then you can do:

char[] array = new char[] { '1', '2', '3', '4' };
int[] intArray = array.Where(char.IsDigit)
                      .Select(r => (int) char.GetNumericValue(r))
                      .ToArray();

This will give you the numeric representation not the ASCII value.

Habib
  • 219,104
  • 29
  • 407
  • 436
0

Using LINQ ?

char[] array = value.ToCharArray(); 
int[] newarray = array.Select(c => (int)c).ToArray();
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
0

You can use Array.ConvertAll:

int[] ints = Array.ConvertAll<char, int>(chars, c => (int) c);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939