tag:blogger.com,1999:blog-8882389959394402329.post6094002545308858979..comments2024-03-21T03:31:50.431-04:00Comments on Chris Lalancette: Writing Ruby Extensions in C - Part 7, NumbersChrishttp://www.blogger.com/profile/12412311785503355784noreply@blogger.comBlogger1125tag:blogger.com,1999:blog-8882389959394402329.post-24783025358667658402011-01-21T12:40:35.125-05:002011-01-21T12:40:35.125-05:00There's one annoying thing about Bignums. Exte...There's one annoying thing about Bignums. Extension API provides us only with their methods, and all of them convert the value into Fixnum whenever possible. Thus when doing any nontrivial arithmetic with bignums, we are to take care of the first argument to make sure it's Bignum.<br /><br />For example, suppose we want to find (x/2 + 1) where x is Bignum. We can't just write rb_big_plus(rb_big_div(x,rb_int2big(2)), rb_int2big(1)) because rb_big_plus was designed as Bignum' method and we have no idea whether x/2 is Bignum or not.<br /><br />As for me, I use macros:<br />#define TO_BIGNUM(x) (FIXNUM_P(x) ? rb_int2big(FIX2LONG(x)) : x)<br />#define BEXPR(x,expr) (FIXNUM_P(x) ? x=TO_BIGNUM(x), expr : expr)<br /><br />(the second one is useful in such cases as rb_big_mul(x,x) so to convert x only once)lomereiterhttps://www.blogger.com/profile/00185471803062906653noreply@blogger.com