Search code examples
c#type-conversionhexasciiapdu

Convert ASCII Console Input to Hex


I'm programming in c# and trying to convert a console input to Hex. Input is a number between 1-256 (ex. 125) The converted number should look like this:

fpr 125: 0x31, 0x32, 0x35

I already tried to solve my problem for hours by using:

byte[] array = Encoding.ASCII.GetBytes(Senke)

but it always shows me byte[].

I need this conversion for creating an APDU to write Information on my smartcard by using my SmartCard Application the final Apdu will look like this:

{ 0xFF, 0xD6, 0x00, 0x02, 0x10, 0x31, 0x32, 0x35}

I hope that someone can help me with this.


Solution

  • To convert integer to hex, use: (more information can be found here)

    int devValue = 211;
    string hexValue = decValue.ToString("X");
    

    To further elaborate, the following will produce your desired output:

    string input = "125"; // your input, could be replaced with Console.ReadLine()
    
    foreach (char c in input) {
        int decValue = (int)c; // Convert ASCII character to an integer
        string hexValue = decValue.ToString("X"); // Convert the integer to hex value
    
        Console.WriteLine(hexValue);
    }
    

    Code would produce the following output:

    31
    32
    35