How to create an integer variable in hexadecimal?

Asked

Viewed 145 times

1

I am trying to create an integer variable in hexadecimal, but an error occurs saying it is not in the correct format.

[DllImport("user32.dll")]
public static extern short GetKeyState(int vKey);
static void Main(string[] args)
{
    string[] lines = File.ReadAllLines("config.txt");
    int TriggerButton = int.Parse(lines[0].Replace("Trigger Button: ", ""));
    int PanicButton  = int.Parse(lines[1].Replace("Panic Button: ", ""));
    Console.WriteLine(TriggerButton + "\n" + PanicButton);
    while (true)
    {
        Console.WriteLine(GetKeyState(TriggerButton));
    }
    Console.ReadKey();
}

Config.txt

Trigger Button: 0x12
Panic Button: 0x78

Have some way to convert a string to a hexadecimal integer without losing the 0x?

  • From what I understand you want to take a string in hexadecimal format and turn into integer. Follows Fiddle with the answer below!

1 answer

1


Without using Stringformat, a valid option is to use

Convert.ToInt32 Method (String, Int32)

Int32 will be the base, in this case 16 Hexadecimal

int PanicButton = Convert.ToInt32(lines[1].Replace("Panic Button: ", ""), 16);

int TriggerButton = Convert.ToInt32(lines[0].Replace("Trigger Button: ", ""), 16);

Browser other questions tagged

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