Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
980 views
in Technique[技术] by (71.8m points)

c - What happens when casting floating point types to unsigned integer types when the value would overflow?

I'm wondering what happens when casting from a floating point type to an unsigned integer type in C when the value can't be accurately represented by the integer type in question. Take for instance

func (void)
{
float a = 1E10;
unsigned b = a;
}

The value of b I get on my system (with unsigned on my system being able to represent values from 0 to 232-1) is 1410065408. This seems sensible to me because it's simply the lowest order bits of the result of the cast.

I believe the behavior of operations such as these is undefined by the standard. Am I wrong? What can I expect in practice if I do things like this?

Also, what happens with signed types? If b is of type int, I get -2147483648, which doesn't really make sense to me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In both cases value is out of range, so it's undefined behaviour.

6.3.1.4 Real floating and integer

  1. When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined. 61)

61) The remaindering operation performed when a value of integer type is converted to unsigned type need not be performed when a value of real floating type is converted to unsigned type. Thus, the range of portable real floating values is (?1, Utype_MAX+1).

To make this well defined code, you should check that value is within possible range before doing the conversion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...