See if number is smaller than 2^32

  • A+

I am reading a huge chunk of numbers via the stdin and I need to find it, if numbers are in the range of [0,2^32] (probably 2^32-1, I am not sure with that), so it’s also not accepting negative numbers. There are also situations where there is a number beginning with hundreds of nulls, which I need to ignore. I am sure if I am doing something wrong with the data type, at the moment I am using „long“ as data type, because I thought this is always with a maximum of 2^32. so if there is an overflow, I am getting a negative number and I can prove if the long is smaller than 0. But now I realised the size of long is also depending on the system of the computer.

Is there anyone who can tell me which data type and operation I should choose to proof this? The beginning datatype is just a char pointer.


You cannot detect overflow of a 32 bit number by using a 32 bit number. If it is unsigned it will always be understood as a number between 0 and 2^32 -1. A overflowing input would still result is a valid out. A signed 32 bit value would be "valid" in the range 0 - 2^31-1. Negative values you would be considered invalid. An over/under flowing input between -2^31 and 0 or 2^31 and 2^32-1 would result in an invalid negative number. However, you may find that numbers above 2^32 would appear as valid again. I suggest you use a signed 64 bit number and treat negative or large numbers as invalid input. This gives you a much greater range of input values that would be filtered correctly. If for example, input was comma limited and the commas had been omitted, there could still be issues. I would suggest the input number as a string should not exceed a limiting length. The length filter should allow strings that represent numbers above 2^32 but should filter out numbers that would be greater than 2^63. Somewhere in the middle. To test the size of a type use "sizeof()". eg sizeof(long), sizeof(long long) etc. However there are usually explicitly sized integers for your platform. For portability use your own types and using a typedef and keep the platform dependent code localised to an include file dedicated to platform dependency only.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: