0

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.

DaveShaw
  • 48,792
  • 16
  • 106
  • 133
Matt
  • 11
  • 1

2 Answers2

0

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
Community
  • 1
  • 1
erikvimz
  • 4,413
  • 5
  • 38
  • 57
  • thank you so far, now i get the output without the 0x and i need it for this function, i need for each number a byte as a variable, for example a=0x31, b=0x32, c=0,35 to use it in this APDU byte[] WriteAPDU = { 0xFF, 0xD6, 0x00, 0x02, 0x10, 0x31, 0x32, 0x35} – Matt Dec 22 '14 at 12:47
0

Here is an example:

int d = 65;  // Capital 'A'

string h= d.ToString("X");  // to hex
int d2 = int.Parse(h, System.Globalization.NumberStyles.HexNumber); //to ASCII
T McKeown
  • 12,312
  • 1
  • 21
  • 30