简体   繁体   English

将 float 指针类型转换为 char 指针时会发生什么?

[英]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.这输出 51。

You can cast a float* to a char* just fine, it's the using of such a beast that may be problematic.您可以float*转换为char*就好了,使用这样的野兽可能会有问题。

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.当您取消引用它时,您将简单地获得 float 的第一部分的char表示形式(但请参阅下文以了解这的真正含义,它并不像您想象的那么清楚)。

If you're talking about IEE754 floats, 12.2 in IEEE754 float is (abcd are the octets):如果您谈论的是 IEE754 浮点数,则 IEEE754 浮点数中的 12.2 是(abcd 是八位字节):

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.最后的00110011是您看到的 51 (0x33)。 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.这意味着float*char* * 转换将指向dddddddd部分。

On big-endian architectures, you would get the aaaaaaaa bit, 01000001 , or 65 (0x41).在大端架构上,您将获得aaaaaaaa位、 01000001或 65 (0x41)。

  1. You cast to (char) instead of (char*).您转换为 (char) 而不是 (char*)。
  2. You print it out as integer.您将其打印为整数。
  3. Thus you get the least significant byte of f's address.这样你就得到了 f 地址的最低有效字节。

EDIT: According to the new markup you really truncate the float representation to its least significant byte (on little-endian machines)编辑:根据新的标记,你真的将浮点表示截断为其最低有效字节(在小端机器上)

Mostly what EFraim says, except that you did cast to char*, only the stackoverflow markup was wrong.主要是 EFraim 所说的,除了你确实转换为 char*,只有 stackoverflow 标记是错误的。

So you get the least significant byte of f's internal representation (in IEEE-754).所以你得到了 f 内部表示的最低有效字节(在 IEEE-754 中)。

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.浮点数有一个相当复杂的编码,所以它与你放在浮点数中的数字没有明显的关系。

The question is:问题是:

what happens when float is typecasted to char pointer将 float 类型转换为 char 指针时会发生什么

The precise answer is:准确的答案是:

Undefined Behavior.未定义的行为。

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.你的问题有点偏差我跑题了,我通常在这种情况下使用 snpritf示例:首先格式化然后你可以播放格式化的缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM