Literals/Integer

From Rosetta Code
Revision as of 00:08, 2 February 2009 by rosettacode>Spoon! (added java)
Task
Literals/Integer
You are encouraged to solve this task according to the task description, using any language you may know.

Some programming languages have ways of expressing integer literals in bases other than the normal base ten.

Show how integer literals can be expressed in as many bases as your language allows.

Note: this should not involve the calling of any functions/methods but should be interpreted by the compiler or interpreter as an integer written to a given base.


AWK

<lang>BEGIN {

   if ( (0x2d7 == 727) &&
        (01327 == 727) ) {
       print "true"
   }

}</lang>

C

Leading 0 means octal, 0x or 0X means hexadecimal. Otherwise, it is just decimal.

<lang c>#include <stdio.h>

int main() {

 printf("%s\n",

( (727 == 0x2d7) && (727 == 01327) ) ? "true" : "false"); }</lang>

C has no way of specifying integers in binary (if there's something like 0b..., it is not standard)


Fortran

<lang fortran>program IntegerLiteral

 implicit none
 integer, parameter   :: dec = 727
 integer, parameter   :: hex = Z'2d7'
 integer, parameter   :: oct = O'1327'
 integer, parameter   :: bin = B'1011010111' 
 print *, dec, hex, oct, bin

end program IntegerLiteral</lang>

Outputs:

         727         727         727         727

Haskell

(This is an interactive ghci session)

Oct(leading 0o or 0O), Hex(leading 0x or 0X) <lang haskell> Prelude> 727 == 0o1327 True Prelude> 727 == 0x2d7 True </lang>

Java

Leading 0 means octal, 0x or 0X means hexadecimal. Otherwise, it is just decimal.

<lang java> public class IntegerLiterals {

   public static void main(String[] args) {
       System.out.println( 727 == 0x2d7 && 

727 == 01327 );

   }

}</lang>

Java has no way of specifying integers in binary

OCaml

(This is an interactive ocaml session)

Bin(leading 0b or 0B), Oct(leading 0o or 0O), Hex(leading 0x or 0X) <lang ocaml>

  1. 727 = 0b1011010111;;

- : bool = true

  1. 727 = 0o1327;;

- : bool = true

  1. 727 = 0x2d7;;

- : bool = true </lang>

Perl

<lang perl> print "true\n" if ( (727 == 0x2d7) && (727 == 01327) && (727 == 0b1011010111) ); </lang>


Python

Works with: Python version 2.5

<lang python>>>> # Oct(leading 0), Dec, Hex(leading 0x or 0X), in order: >>> 01327 == 727 == 0x2d7 True >>> </lang>

Works with: Python version 3.0

<lang python>>>> # Bin(leading 0b or 0B), Oct(leading 0o or 0O), Dec, Hex(leading 0x or 0X), in order: >>> 0b1011010111 == 0o1327 == 727 == 0x2d7 True >>> </lang>

Ruby

(This is an interactive ruby session)

irb(main):001:0> 727 == 0b1011010111
=> true
irb(main):002:0> 727 == 0x2d7
=> true
irb(main):003:0> 727 == 01327
=> true