Question

 short c = 34;

and the hex value of c is 22. How can I assign the hex value to a short variable (say short d) by converting 'c'?

like

   short d = 22;
Was it helpful?

Solution 4

Use a string buffer and sprintf hex format.

Then write it back with atoi as below

#include <stdio.h>
#include <stdlib.h>

int main()
{
  short c = 34;
  short d;
  char string[10];
  sprintf(string, "%x", c);
  d = atoi(string);
  printf("c = %d\n", c);
  printf("d = %d\n", d);
  return 0;
}

gives output

c = 34
d = 22

OTHER TIPS

short objects and other integer objects do not have decimal values or hexadecimal values. Their values are pure numbers.

Eleven, 11, and 0xb are different names for the same number.

To assign d the same value as c, use d = c;.

When you print with printf, you can have values formatted as decimal numerals or hexadecimal numerals. You can print the value of c as a hexadecimal numeral with printf("%x", c);.

You don't need to do any type of conversion when assigning from one short to another. To the PC, it's just a collection of bits. How you interpret them (as hex, decimal, etc.), is a high-level decision you code around. If you have the correct hex (or otherwise) value in "c", just assign it to "d."

Machine knows nothing about numeral systems. They are for human perception of numbers.

You must only "translate" numbers when human-machine interaction happens:

  • from human form to machine form on input (human >> machine)
  • from machine form to human form on output (machine >> human)

Example of output:

short c = 10; // for you its "decimal ten" now, 
              // for machine is just a handful of bits
printf("d = %d\n", c);   // you explicitly say here to output as decimal
printf("d = 0x%.4X", c); // you explicitly say here to output as hexadecimal

So instead of trying to translate inside of logic part of program, go down to output part and translate there.

Hope it helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top