2

I have the following numbers which I read from a file.
These numbers are read as strings. I need to represent them as hexadecimal numbers.
How do I do that?

00000004
00000008
00000009
0000000d
00000100
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55

2 Answers2

3

Since you want to read these numbers from a file, fscanf is helpful for this:

/* note, if you're using more than 8 digits, 
    this would have to be unsigned long long and instead of %lx you would need %llx */
unsigned long h;
if (fscanf(f, "%lx", &h) == 1)
    do whatever with h
else
    error, check errno

You can use this check in a loop while (fscanf(f, "%x\n", &h) == 1); to read until the last number.

  • 1
    Better use `unsigned h;`. – alk Dec 24 '13 at 17:21
  • Yeah, thanks! 3more to go –  Dec 24 '13 at 17:25
  • 1
    `"\n"` in `"%x\n"` serves no purpose. Suggest eliminating it. `"%x"` consumes leading whitespace already. `fscanf(f, "%x\n", &h)` will return 1 with or without a `\n` following the number. – chux - Reinstate Monica Dec 24 '13 at 22:17
  • "if you're using more than **4** digits, ...." as `unsigned` is only at least 0 to 65535. Better to use `unsigned long` here. – chux - Reinstate Monica Dec 24 '13 at 22:20
  • @chux `unsigned` defaults to `unsigned long int` anyway. Now it is `unsigned long` to make more sense. –  Dec 26 '13 at 00:32
  • 2
    @user9000 Suggest `"%lx\n"` to go with `unsigned long`. BTW: "unsigned defaults to unsigned long int" is _not_ so. `unsigned`, same as `unsigned int`, does not default to anything other than it has at least the range of `unsigned short` and no more range than `unsigned long`. By the C spec §5.2.4.2.1, the minimum `unsigned` range is the same as minimum `unsigned short` range. – chux - Reinstate Monica Dec 26 '13 at 01:01
3

If you have already read them into a character buffer, you could use strtol to convert from base 16 (pass 16 as the 3rd parameter).

Alternatively, if you are reading them from the file, you could fscanf with the %x conversion specifier.

Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110