-5

I want to convert the key stroke representation to its decimal from. eg :- the input string is

^@^D^@^A49

This should be converted to 0004000149 ie ^@ - 00 ^D -04 ^A -01 I found the correct values from the below link

http://techurls.tripod.com/dha.htm

Edit:-

The main problem is to map the values ie ^@ - 00 ^D -04 ^A -01

Is there any standard lib function or This is needed to be done using switch case?

anurag
  • 82
  • 2
  • 10

1 Answers1

3

I believe you have misunderstood the concepts involved a little bit:

First, "^@^D^@^A49" is not a sequence of hexadecimal digits, it is a visualization of keystrokes. ^@ == CTRL+@ for instance.

Hexadecimal numbers are numbers written on the following form:

0xFF00AB12, that is numbers with radix 16. 0 == 0, 1 == 1, ..., 9 == 9, A == 10, B == 11, ..., F == 15. (The 0x is just a standard prefix used to distinguish a hex value from say a binary or decimal number).

If your aim is to initialize a string or integer with full control of where the bits go, I would recommend reading the input from the keyboard as a string of hexadecimal digits (with or without the prefix, your choice.)

Once you have done that, you may use for instance sscanf to read the string into an integer.

int sscanf ( const char * s, const char * format, ...);

Example:

const char * hexstring = "FF800001";
unsigned int value;
sscanf(hexstring, "%x", &value);
Stian Svedenborg
  • 1,797
  • 11
  • 27
  • If you enter the prefix, you may have to strip it again before passing it to sscanf. – Stian Svedenborg Jul 14 '14 at 11:32
  • Actually the sequence has to be parsed from a file not from keyboard so I have no option but to parse and convert ^@^D^@^A into decimal form. – anurag Jul 14 '14 at 11:48
  • 1
    Then you should instead use binary input. http://stackoverflow.com/questions/24716250/c-store-read-binary-file-into-buffer/24717935#24717935 as that will take care of the conversion for you. – Stian Svedenborg Jul 14 '14 at 12:58
  • @StianV.Svedenborg _'Then you should instead use binary input ...'_ Huh what? – πάντα ῥεῖ Jul 14 '14 at 17:35
  • I'm inferring that he is seeing ^@^D etc because he's trying to open binary file in text mode (in an editor that will show them as such). I can't think of any other reason he would have to see that, unless he's been copying similar output from another source. But I find that less likely. – Stian Svedenborg Jul 14 '14 at 18:30
  • 1
    Its solved by opening file in binary mode. Here is the code that worked :) const char * fname = "filename"; char Event_label[2]; char val[2]; int value; FILE* filp = fopen(fname, "rb" ); if (!filp) { printf("Error: could not open file %s\n", fname); return -1; } char * buffer = new char[BUFFERSIZE]; fseek(filp, 0, SEEK_SET); fread(&Event_label, sizeof(char)*4, 1, filp); printf("<%-.2s>",Event_label); printf("i= %d%d",Event_label[0],Event_label[1]); – anurag Jul 18 '14 at 12:32