srie raam
srie raam

Reputation:

What happens when float pointer is typecasted to char pointer?

int main()
{
    float f = 12.2;
    char *p1;
    p1 = (char *)&f;
    printf ("%d", *p1);
}

This outputs 51.

Upvotes: 1

Views: 3894

Answers (6)

chandu
chandu

Reputation: 113

There is slight deviation to your question I am off the topic,I usually use in such cases the snpritf Example:to fisrt format and then you can play the formatted buffer.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881103

You can cast a float* to a char* just fine, it's the using of such a beast that may be problematic.

When you de-reference it, you'll simply get the char representation of the first part (but see below to understand what this really means, it's not as clear as you may think) of the float.

If you're talking about IEE754 floats, 12.2 in IEEE754 float is (abcd are the octets):

S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM (sign, exponent, mantissa).
0 10000010 10000110011001100110011
a aaaaaaab bbbbbbbccccccccdddddddd

The 00110011 at the end is the 51 (0x33) that you're seeing. The reason you're seeing the last bit of the float is because it's stored like this in memory (in a little-endian architecture):

00110011 00110011 01000011 01000001
dddddddd cccccccc bbbbbbbb aaaaaaaa

which means that the char* cast of the float* will point at the dddddddd part.

On big-endian architectures, you would get the aaaaaaaa bit, 01000001, or 65 (0x41).

Upvotes: 17

EFraim
EFraim

Reputation: 13028

  1. You cast to (char) instead of (char*).
  2. You print it out as integer.
  3. Thus you get the least significant byte of f's address.

EDIT: According to the new markup you really truncate the float representation to its least significant byte (on little-endian machines)

Upvotes: 1

Pavel Minaev
Pavel Minaev

Reputation: 101555

The question is:

what happens when float is typecasted to char pointer

The precise answer is:

Undefined Behavior.

Upvotes: 0

Chris Arguin
Chris Arguin

Reputation: 11998

Assuming the other issues mentioned are fixed, you are getting the integer version of whatever the bit pattern happens to be for that float. Floats have a fairly complicated encoding, so it will be nothing obviously related to the number you put in the float.

Upvotes: 1

Martin v. Löwis
Martin v. Löwis

Reputation: 127447

Mostly what EFraim says, except that you did cast to char*, only the stackoverflow markup was wrong.

So you get the least significant byte of f's internal representation (in IEEE-754).

Upvotes: 1

Related Questions