Bitwise or cause overflow when num > 2147483647

Refer to this article: math-round-vs-hack

We have Math functions optimized.

We use (num+0.5)|0 instead of Math.round().

But there's a problem which make confused that when num > 2147483647, it comes out wrong results.

function round(n) { return (n + 0.5) | 0; };

round(2147483648) will return -2147483648

And according to wikipedia:

2147483647 in computing

The number 2,147,483,647 is also the maximum value for a 32-bit signed integer in >computing. It is therefore the maximum value for variables declared as int in many >programming languages running on popular CPUs, and the maximum possible score (or amount >of money) for many video games. The appearance of the number often reflects an error, >overflow condition, or missing value.[8] Similarly, "(214) 748-3647" is the sequence of >digits represented as a United States phone number and is the most common phone number >listed on web pages.[9] The data type time_t, used on operating systems such as Unix, is a 32-bit signed integer >counting the number of seconds since the start of the Unix epoch (midnight UTC of 1 >January 1970).[10] The latest time that can be represented this way is 03:14:07 UTC on >Tuesday, 19 January 2038 (corresponding to 2,147,483,647 seconds since the start of the >epoch), so that systems using a 32-bit time_t type are susceptible to the Year 2038 >problem.[11]

How can I handle this situation to ensure good performance?

-------------Problems Reply------------

Short answer: Use Math.round()

I would file this entire exercise under "why you should never do micro optimizations". Take a look at this fiddle: http://jsfiddle.net/toxicsyntax/a5rWm/2/

Here is some results from different browsers:

  • Firefox 11: round: 185ms bit_round: 123ms (for 100000000 iterations)
  • Chrome 18: round: 99ms bit_round: 96ms (for 100000000 iterations)
  • IE 9: round: 227ms bit_round: 123ms (for 1000000 iterations)
  • IPhone 4, Safari: round 399ms, bit_round 32ms (for 1000000 iterations)

Sure, in the best case the bitwise round function is way faster than using Math.round(), but does it really matter? Worst case Math.round() still handles several millions rounds pr. seconds without problems.

How many do you roundings do you have to do? I don't expect you would ever have to round numbers in javascript, except for displaying numbers, and even if you are displaying thousands of rounded numbers pr. second, Math.round() is still going to be fast enough for you.

Update

And also, regarding micro optimazations in general, be sure to check out the article from Coding Horror: http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html

Micro optimazation is very, very rarely a good idea.

Category:javascript Views:0 Time:2012-04-18

Related post

  • Ruby: What does the snippet: (num & 1) == 0 exactly do? 2010-11-06

    I was watching a metaprogramming video from PragProg, and Dave Thomas showed this snippet of code: module Math class << self def is_even?(num) (num & 1) == 0 # What exactly is going on here? Particularly (num & 1) end end end puts Math.

  • How to emulate 4-bit integer in Python 3? 2014-05-17

    I'd like to emulate overflow behavior of unsigned 4-bit integers, like this: >>> x, y = Int4(10), Int4(9) >>> x + y Int4(3) >>> x * y Int4(10) Inheritance of builtin int seems to work. Is it possible to implement Int4 class

  • Perl pack/unpack/shift 2010-07-07

    I've been having this problem in Perl for a few days now, and after scouring countless man pages, perldocs and googling too many search terms, hopefully someone here can help me out. I am given two strings which represent hex values, i.e. "FFFF", not

  • C# Implicit/Explicit Type Conversion 2011-02-21

    I have a simple scenario that may or may not be possible. I have a class that contains an integer, for this purpose I'll make it braindead simple. public class Number { public int Value {get; set;} public string Name {get; set;} } public static void

  • What can cause keys added to a Hashtable to be null? 2011-04-27

    Using the .NET Micro Framework 4.1 I'm adding the following string keys (and string values, not relevant here) to a hashtable: "eth::address" "eth::netmask" "eth::gateway" "eth::dns" "eth::port" "com::baudrate" "com::parity" "com::databits" "com::sto

  • Most efficient way to store thousand telephone numbers 2011-10-07

    This is a google interview question: There are around thousand phone numbers to be stored each having 10 digits. You can assume first 5 digits of each to be same across thousand numbers. You have to perform the following operations: a. Search if a gi

  • Parsing numbers in FParsec 2012-02-06

    I've started learning FParsec. It has a very flexible way to parse numbers; I can provide a set of number formats I want to use: type Number = | Numeral of int | Decimal of float | Hexadecimal of int | Binary of int let numberFormat = NumberLiteralOp

  • C - can sscanf read from the same string it's writing to? 2012-04-16

    I have the following code int myInt; sscanf(str, "%d=%s", &myInt, str); Will this be valid? Is there a better way to do this if I have it in a loop? --------------Solutions------------- My guess is that this wil usually work because it seems like

  • Regexp only integer issue 2013-12-22

    I found this regexp for integers from range -2147483648 to 2147483647. (0|[1-9]{1}[0-9]{0,8}|[1]{1}[0-9]{1,9}|[-]{1}[2]{1}([0]{1}[0-9]{8}|[1]{1}([0-3]{1}[0-9]{7}|[4]{1}([0-6]{1}[0-9]{6}|[7]{1}([0-3]{1}[0-9]{5}|[4]{1}([0-7]{1}[0-9]{4}|[8]{1}([0-2]{1}[

  • Relocation overflow when performing bitwise AND (SPARC Assembly)? 2010-10-15

    I am trying to perform a bitwise AND on a register, as a bitmask to remove the most significant bit (which happens to be bit 16 when counting from 0). However, when I try to compile my code using gcc, it gives me the following error messages: Assembl

  • Bitwise overflow checking in c 2012-04-09

    I am trying to write two functions that will check/prevent overflow in c (using only ! ~ | & ^ +) but cant get it. The first is will a certain twos compliment/signed int will fit in a certatin amount of bits: fitsB(int x, int n) where is the int

  • Bitwise operation and usage 2009-11-17

    Consider this code: x = 1 # 0001 x << 2 # Shift left 2 bits: 0100 # Result: 4 x | 2 # Bitwise OR: 0011 # Result: 3 x & 1 # Bitwise AND: 0001 # Result: 1 I can understand the arithmetic operators in Python (and other languages), but I never

  • Determine if conversion from string to 32-bit integer will overflow 2010-02-17

    Trying to do front-end validation on an HTML input instead of throwing an exception in the Java back-end. --------------Solutions------------- if ((the_number >> 0) != the_number) { // overflow... } You still need a server-side check because th

  • How to implement " char * ftoa(float num) " without sprintf() library function in C, C++ and JAVA? 2010-02-20

    Today I appeared for an interview, and the question was writing my own "char * ftoa(float num) " in C, C++ and Java. Yes, I know float numbers follow IEEE standard while allocating their memory, but I don't know float to char conversion by using Mant

  • How does Java handle integer underflows and overflows and how would you check for it? 2010-06-08

    How does Java handle integer underflows and overflows? Leading on from that, how would you check/test that this is occurring? --------------Solutions------------- If it overflows, it goes back to the minimum value and continues from there. If it unde

  • bitwise arithmetic tutorial 2012-02-17

    I'm looking for tutorials which talk about bitwise arithmetic operations, such as addition, substraction, multiplication and division, maybe other operators more complicated like modular, inverse modular etc. Actually I'm trying to implement a big nu

  • Check whether multiplication will overflow 2008-10-13

    I was writing a program in C++ to find all solutions of ab = c, where a, b and c together use all the digits 0-9 exactly once. The program looped over values of a and b, and ran a digit-counting routine each time on a, b and ab to check if the digits

  • How to detect integer multiplication overflow in Visual Studio C++ 2008-10-13

    I was writing a program in C++ to find all solutions of ab = c, where a, b and c together use all the digits 0-9 exactly once. The program looped over values of a and b, and ran a digit-counting routine each time on a, b and ab to check if the digits

  • What are bitwise operators? 2008-11-09

    I'm someone who writes code just for fun and haven't really delved into it in either an academic or professional setting, so stuff like these bitwise operators really escapes me. I was reading an article about JavaScript, which apparently supports bi

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.191 (s). 11 q(s)