From r|p|ey @end|ng |rom @t@t@@ox@@c@uk  Thu Aug 12 09:57:28 2021
From: r|p|ey @end|ng |rom @t@t@@ox@@c@uk (Prof Brian Ripley)
Date: Thu, 12 Aug 2021 08:57:28 +0100
Subject: [Rd] Double to uint64_t on M1
In-Reply-To: <C582D4F5-6218-42CC-AC63-50CAB13D977E@R-project.org>
References: <EE649952-4BB6-432A-B3CA-BD9B11DD9324@gmail.com>
 <C582D4F5-6218-42CC-AC63-50CAB13D977E@R-project.org>
Message-ID: <735e0e1e-4419-6bc2-2a02-6a3f683197b6@stats.ox.ac.uk>

On 12/08/2021 04:52, Simon Urbanek wrote:
> 
> Dipterix,
> 
> this has nothing to do with R. 2^63 is too large to be represented as singed integer, so the behavior is undefined - to quote from the C99 specs (6.3.1.4):
> 
> "If the value of the integral part cannot be represented by the integer type, the behavior is undefined."
> 
> Your subject doesn't match your question as the uint64_t conversion is well-defined and the same on both platforms, but the conversion to int64_t in undefined.

As I was writing a reply to say the same thing, a few more comments.

- the example is actually in C++, but also undefined there.

- R is more careful:
 > as.integer(2^31)
[1] NA
Warning message:
NAs introduced by coercion to integer range

- there is a sanitizer for this, on platforms including Linux and macOS 
(at least with clang, 
https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#supported-platforms).

> 
> Cheers,
> Simon
> 
> 
>> On 12/08/2021, at 10:50 AM, Dipterix Wang <dipterix.wang at gmail.com> wrote:
>>
>> Hi,
>>
>> I was trying to convert REALSXP to int64_t in C, then found that converting 2^63 is inconsistent across platforms:
>>
>>
>> On M1 ARM osx, 2^63 (double) bit converting to `int64_t` becomes 9223372036854775807
>> On x86_64 ubuntu server, 2^63 (double) bit converting to `int64_t` is -9223372036854775808
>>
>> I was wondering if this is desired behavior to R?
>>
>> Here's the code to replicate the results above.
>>
>> print_bit <- Rcpp::cppFunction(r"(
>> SEXP print_bit(SEXP obj){
>>
>>   int64_t tmp1 = *REAL0(obj);
>>   printf("%lld ", tmp1);
>>
>>   return(R_NilValue);
>> }
>> )")
>>
>> print_bit(2^63)
>>
>> Thanks,
>> - Dipterix
>> 	[[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-devel at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-devel
>>
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
> 


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Emeritus Professor of Applied Statistics, University of Oxford



[Rd] Double to uint64_t on M1
Prof Brian Ripley