0

I am aware that when using the printf function I can express the octal value of an integer with %o and its hexadecimal value with %x.
How can I represent a floating-point value as octal or hexadecimal, though?
When trying to use the same specifiers, Xcode 13.x predictably throws a warning telling me I am trying to use an integer specifier with a floating-point value.

How can I work around this?
Thank you

NotationMaster
  • 390
  • 3
  • 17
  • If you want to print an **octal** number the way `%a` prints a hexadecimal number, you can do the following: Build the hexadecimal representation using `sprintf(..."%a"...)`. `171.75` would result in `AB.C`. Convert each hexadecimal digit to 4 binary digits: `AB.C` becomes `10101011.1100`. Remove or add leading zeroes before and trailing ones after the decimal point so the number of digits before and after the point is divisible by 3. Convert 3 binary digits to octal. `010101011.110` becomes `253.6` which is the octal representation of `171.75`. – Martin Rosenau Jan 08 '22 at 13:19
  • Thank you. How would I do this in code? Your procedure is what I would do "manually" – NotationMaster Jan 08 '22 at 13:45

1 Answers1

1

You can format a float or double in hexadecimal using %a or %A (to use lowercase or uppercase letters, respectively). There is no conversion specifier for octal for floating-point.

This formats the value. If you want to view the representation of the floating-point object, you should access its bytes using an unsigned char *, and then you can format those bytes using the o, x, or X conversion specifiers.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312