Using the linux command line in bash as a programmer's calculator

Comments (in chronological order):

Reply to the article

Name:

Your comment:


Enter this:

Emily Chen said:...
Re. the section on floating point conversions: The cast expression (e.g. `(float *)` in `print/x (float *) ...`) is both incorrect and superfluous.

Loosely speaking, `(float *) 1` does not reinterpret the bit pattern for integer value `1` as a float; instead, it effectively reinterprets the value (converting/extending if necessary) to a pointer value (usu. a 32-bit or 64-bit memory address depending on architecture).
* For example, on an architecture where pointers (e.g. `float*`) are 64-bit memory address, this extends the integer value to 64 bits before reinterpreting as floating point (which would make gdb interpret it as the `double` type)
* In your example (`print/f (float *) 0x449a5224`), presumably this was on a 32-bit-addressed arch, and therefore it gave the correct result.

The correct way to ensure the input value is of the correct type and width, is to use either
* a literal suffix - e.g. `0x449a5224`/`0x449a5224l`/`0x449a5224ll`, `1234.567f`/`1234.567d`
* or an explicit typecast - e.g. `(int)`/`(long int)`/`(long long int) 0x449a5224`, `(float)`/`(double) 1234.567` (like your first example).
11/8/2022 11:55
Emily Chen said:...
(2/2) The actual conversion is performed by gdb's output formatter, e.g.
* `/d` to reinterpret as signed integer type (of same width) & print in decimal
* `/u`, `/x`, `/o` to reinterpret as unsigned integer (of same width) & print in decimal/hex/octal/etc
* `/f` to reinterpret as floating point (of same width) and print in decimal

(https://sourceware.org/gdb/current/onlinedocs/gdb/Output-Formats.html)
11/9/2022 12:00