Literals/Integer

From Rosetta Code
Revision as of 22:22, 29 January 2010 by 91.168.179.243 (talk) (→‎{{header|Standard ML}}: {{Lines_too_long}})
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.

Also show any other ways of expressing literals, e.g. for different types of integers.

Ada

In Ada integer literals may have the form <base>#<numeral>#. Here <base> can be from the range 2..16. For example: <lang ada>with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Test_Literals is begin

  Put (16#2D7#);
  Put (10#727#);
  Put (8#1_327#);
  Put (2#10_1101_0111#);

end Test_Literals;</lang> Sample output:

        727        727        727        727

ALGOL 68

Translation of: Fortran
Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386

Binary constants are of type BITS, and need to be converted to INT using the operator ABS. <lang algol68>main:(

 INT dec = 727;
 INT hex = ABS 16r2d7;
 INT oct = ABS 8r1327;
 INT bin = ABS 2r1011010111;

 print((dec, hex, oct, bin, new line))

)</lang> Output: <lang algol68>+727 +727 +727 +727</lang>

AmigaE

<lang amigae>PROC main()

 IF ($2d7 = 727) AND (%001011010111 = 727) THEN WriteF('true\n')

ENDPROC</lang>

AutoHotkey

<lang AutoHotkey>If (727 == 0x2d7) MsgBox true</lang>

AWK

<lang awk>BEGIN {

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

}</lang>

BASIC

&O = octal; &H = hexadecimal. Some flavors of BASIC also support &B = binary, but they're somewhat rare.

<lang basic>PRINT 17 PRINT &O21 PRINT &H11 </lang> Output:

17
17
17

C

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

<lang c>#include <stdio.h>

int main(void) {

 printf("%s\n",
        ( (727 == 0x2d7) && 
          (727 == 01327)    ) ? "true" : "false");
 return 0;

}</lang>

GCC supports specifying integers in binary using the 0b prefix syntax, but it's not standard. Standard C has no way of specifying integers in binary.

To specify a literal of an unsigned integer, you add the suffix "u" or "U". To specify a literal of a "long" integer, you add the suffix "l" or "L". In C99, to specify a literal of a "long long" integer, you add the suffix "ll" or "LL". (The "l" and "ll" forms are discouraged as "l" looks like the digit "1"). The "u" suffixes can be combined with "l" or "ll" suffixes for unsigned long or unsigned long long integers.

C++

The same comments apply as to the C example.

<lang cpp>#include <iostream>

int main() {

 std::cout << ( (727 == 0x2d7) && 
                (727 == 01327)     ? "true" : "false")
           << std::endl;

 return 0;

}</lang>

Clojure

Clojure uses the Java octal (0...) and hexadecimal (0x...) notation; for any other base, nR... is used, 2 <= n <= 36.

<lang lisp>user=> 2r1001 9 user=> 8r64 52 user=> 064 52 user=> 16r4b 75 user=> 0x4b 75 user=></lang>

Common Lisp

(This is an interactive common lisp session)

binary: #b, octal: #o, hexadecimal: #x, any base from 2 to 36: #Nr <lang lisp>>(= 727 #b1011010111) T >(= 727 #o1327) T >(= 727 #x2d7) T >(= 727 #20r1g7) T</lang>

D

D besides hexadecimal, and octal bases has also binary base. Additionaly you can use _ to separate digits in integer literals.

<lang D>import tango.io.Stdout;

int main(char[][] args) {

   Stdout ("oct: ") (0777).newline;
   Stdout ("bin: ") (0b01011010).newline;
   Stdout ("hex: ") (0xBADF00D).newline;
   Stdout ("dec: ") (1000000000).newline;
   Stdout ("dec: ") (1_000_000_000).newline;
   Stdout.newline;
   Stdout (typeid(typeof(0))).newline;
   Stdout (typeid(typeof(0u))).newline;
   Stdout (typeid(typeof(0L))).newline;
   Stdout (typeid(typeof(0uL))).newline;
   Stdout (typeid(typeof(0LU))).newline;
   Stdout.newline;
   Stdout.formatln ("{:x}", 0xFEE1_BAD_CAFE_BABEuL);
   return 0;

}</lang>

Output:

oct: 511
bin: 90
hex: 195948557
dec: 1000000000
dec: 1000000000

int
uint
long
ulong
ulong

fee1badcafebabe

E

<lang e>? 256

  1. value: 256

? 0x100

  1. value: 256

? 0123

  1. syntax error: Octal is no longer supported: 0123</lang>

Forth

The standard method for entering numbers of a particular base is to set the user variable BASE to the desired radix from 2 to 36. There are also convenience words for setting the base to DECIMAL and HEX. <lang forth>HEX FEEDFACE 2 BASE ! 1011001 DECIMAL 1234

mask var @ [ base @ hex ] 3fff and [ base ! ] var ! ;</lang>

The Forth numeric parser will look for symbols embedded within the stream of digits to determine whether to interpret it as a single cell, double cell, or floating point literal ('e'). <lang forth>1234 ( n ) 123.4 ( l h ) 123e4 ( F: n )</lang>

Base prefixes

Works with: GNU Forth

In addition, many Forths have extensions for using a prefix to temporarily override BASE when entering an integer literal. These are the prefixes supported by GNU Forth. <lang forth>$feedface \ hexadecimal &1234 \ decimal %1001101 \ binary 'a \ base 256 (ASCII literal)</lang> Some Forths also support "0xABCD" hex literals for compatibility with C-like languages.

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

Groovy

Solution: <lang groovy>println 025 // octal println 25 // decimal println 0x25 // hexadecimal</lang>

Output:

21
25
37

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>

J

J's numeric mini-language allows spaces, underlines, dots and lower case alphabetic characters in its numeric literals.

Arbitrary base numbers begin with a base ten literal (which represents the base of this number), and then the letter 'b' and then an arbitrary sequence of digits and letters which represents the number in that base. Letters a..z represent digits in the range 10..35.

<lang j> 10b123 16b123 8b123 20b123 2b123 1b123 0b123 100b123 0 123 291 83 443 11 6 3 10203 0</lang>

This may be used to enter hexadecimal or octal or binary numbers. However, note also that J's primitives support a variety of binary operations on numbers represented as sequences of 0s and 1s, like this:

<lang j>0 1 0 0 0 1 0 0 0 1 1 1 1</lang>


J also supports extended precision integers, if one member of a list ends with an 'x' when they are parsed. Extended precision literals can not be combined with arbitrary base literals.

<lang j> 123456789123456789123456789 100000000000x 123456789123456789123456789 100000000000

  16b100 10x

|ill-formed number</lang>

J also allows integers to be entered using other notations, such as scientific or rational.

<lang j> 1e2 100r5 100 20</lang>

Internally, J freely converts fixed precision integers to floating point numbers when they overflow, and numbers (including integers) of any type may be combined using any operation where they would individually be valid arguments.

Java

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

<lang java5>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.

You may also specify a long literal by adding an l or L (the latter form is preferred as the former looks like a "1") to the end (ex: long a = 574298540721727L), and this is required for numbers that are too large to be expressed as an int.

JavaScript

<lang javascript>if ( 727 == 0x2d7 &&

    727 == 01327 )
   window.alert("true");</lang>

Logo only supports decimal integer literals.

M4

<lang M4>eval(10) # base 10 eval(010) # base 8 eval(0x10) # base 16 eval(0b10) # base 2 eval(`0r2:10') # base 2

...

eval(`0r36:10') # base 36</lang>

Output:

10        # base 10
8       # base 8
16      # base 16
2      # base 2
2  # base 2
 ...
36 # base 36

Metafont

<lang metafont>num1 := oct"100"; num2 := hex"100";</lang>

Metafont numbers can't be greater than 4096, so that the maximum octal and hexadecimal legal values are 7777 and FFF respectively. To be honest, "100" is a string, and oct is an "internal" "macro"; but this is the way Metafont specifies numbers in base 8 and 16.

Modula-3

All numbers 2 to 16 are allowed to be bases. <lang modula3>MODULE Literals EXPORTS Main;

IMPORT IO;

BEGIN

 IO.PutInt(16_2D7);
 IO.Put(" ");
 IO.PutInt(10_727);
 IO.Put(" ");
 IO.PutInt(8_1327);
 IO.Put(" ");
 IO.PutInt(2_1011010111);
 IO.Put("\n");

END Literals.</lang>

OCaml

(This is an interactive ocaml session)

Bin(leading 0b or 0B), Oct(leading 0o or 0O), Hex(leading 0x or 0X) <lang ocaml># 727 = 0b1011010111;; - : bool = true

  1. 727 = 0o1327;;

- : bool = true

  1. 727 = 0x2d7;;

- : bool = true

  1. 12345 = 12_345 (* underscores are ignored; useful for keeping track of places *);;

- : bool = true</lang>

Literals for the other built-in integer types:

  • 727l - int32
  • 727L - int64
  • 727n - nativeint

Oz

To demonstrate the different numerical bases, we unify the identical values: <lang oz>try

  %% binary      octal   dec.  hexadecimal
  0b1011010111 = 01327 = 727 = 0x2d7
  {Show success}

catch _ then

  {Show unexpectedError}

end</lang>

Negative integers start with "~": <lang oz>X = ~42</lang>

Perl

<lang perl>print "true\n" if ( 727 == 0x2d7 &&

                   727 == 01327 &&
                   727 == 0b1011010111 &&
                   12345 == 12_345   # underscores are ignored; useful for keeping track of places
                 );</lang>

PHP

<lang php><?php if ( 727 == 0x2d7 &&

    727 == 01327 )
   echo "true\n";

?></lang>

PowerShell

PowerShell only supports base 10 and 16 directly: <lang powershell>727 # base 10 0x2d7 # base 16</lang> Furthermore there are special suffices which treat the integer as a multiple of a specific power of two, intended to simplify file size operations: <lang powershell>3KB # 3072 3MB # 3145728 3GB # 3221225472 3TB # 3298534883328</lang>

Python

Works with: Python version 3.0

Python 3.0 brought in the binary literal and uses 0o or 0O exclusively for octal. <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>

Works with: Python version 2.6

Python 2.6 has the binary and new octal formats of 3.0, as well as keeping the earlier leading 0 octal format of previous 2.X versions for compatability. <lang python>>>> # Bin(leading 0b or 0B), Oct(leading 0o or 0O, or just 0), Dec, Hex(leading 0x or 0X), in order: >>> 0b1011010111 == 0o1327 == 01327 == 727 == 0x2d7 True >>></lang>

Works with: Python version 2.5

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

In Python 2.x you may also specify a long literal by adding an l or L (the latter form is preferred as the former looks like a "1") to the end (ex: 574298540721727L), but this is optional, as integer literals that are too large for an int will be interpreted as a long.

R

0x or 0X followed by digits or the letters a-f denotes a hexadecimal number. The suffix L means that the number should be stored as an integer rather than numeric (floating point). <lang R>0x2d7==727 # TRUE identical(0x2d7, 727) # TRUE is.numeric(727) # TRUE is.integer(727) # FALSE is.integer(727L) # TRUE is.numeric(0x2d7) # TRUE is.integer(0x2d7) # FALSE is.integer(0x2d7L) # TRUE</lang> For more information, see Section 10.3.1 of the R Language definition (PDF).

Ruby

(This is an interactive irb session)

<lang ruby>irb(main):001:0> 727 == 0b1011010111 => true irb(main):002:0> 727 == 0x2d7 => true irb(main):003:0> 727 == 01327 => true irb(main):001:0> 12345 == 12_345 # underscores are ignored; useful for keeping track of places => true</lang>

Scala

Scala has signed integers of 8, 16, 32 and 64 bits. They can be represented in decimal, octal by prefixing 0, or hexadecimal by prefixing 0x or 0X. Without any other type hint, it defaults to 32 bits integers, or an Int. An l or L suffix will indicate a 64 bits integer, or a Long. The other two types, Byte and Short, can be represented using type ascription, as shown below.

scala> 16
res10: Int = 16

scala> 020L
res11: Long = 16

scala> 0x10 : Byte
res12: Byte = 16

scala> 16 : Short
res13: Short = 16

scala> 020 : Int
res14: Int = 16

scala> 0x10 : Long
res15: Long = 16

Scheme

(This is an interactive scheme session)

binary: #b, octal: #o, decimal: #d (optional obviously), hex: #x <lang scheme>> (= 727 #b1011010111)

  1. t

> (= 727 #o1327)

  1. t

> (= 727 #d727)

  1. t

> (= 727 #x2d7)

  1. t</lang>

Slate

<lang slate>2r1011010111 + 8r1327 + 10r727 + 16r2d7 / 4</lang>

Standard ML

Some lines in this example are too long (more than 80 characters). Please fix the code if it's possible and remove this message.

(This is an interactive SML/NJ session)

Hex(leading 0x), Word (unsigned ints, leading 0w), Word Hex (leading 0wx) <lang sml>- 727 = 0x2d7; val it = true : bool - 727 = Word.toInt 0w727; val it = true : bool - 0w727 = 0wx2d7; val it = true : bool - ~727; (* negative number; ~ is the unary negation operator for all numbers, including reals and ints; worth mentioning because it's unusual *) val it = ~727 : int</lang>

Tcl

Works with: Tcl version 8.5

(This is an interactive tclsh session; expr is only called to evaluate the equality test.) <lang tcl>% expr 727 == 0x2d7 1 % expr 727 == 0o1327 1 % expr 727 == 01327 1 % expr 727 == 0b1011010111 1</lang>

TI-89 BASIC

Binary, decimal, and hexadecimal are supported. The system base mode sets the default output base, but does not affect input; unmarked digits are always decimal.

<lang ti89b>0b10000001 = 129 = 0h81</lang>

UNIX Shell

Works with: bash

As manual states, 0x or 0X is the prefix for hexadecimal numbers, while 0 is the one for octal, and nothing means the number is decimal. But the sintax BASE#NUMBER can be used, with BASE going from 2 to 64, and the symbols used are digits, lowercase letters, uppercase letters, @ and _ in that order; if the BASE is less than or equal to 36, lowercase and uppercase letters can be used interchangeably to represent number from 10 and 35. (From the info manual of the Bash). This syntax works only in some circumstances, i.e. in the shell expansion (e.g. inside $(( ))) or using let.

<lang bash>dec=727 oct=$(( 01327 )) bin=$(( 2#1011010111 )) hex=$(( 0x2d7 ))

  1. or e.g.

let bin=2#1011010111 let "baseXX = 20#1g7"</lang>

Ursala

Natural numbers (i.e., unsigned integers) of any size are supported, (among other numeric types). Only decimal integer literals are recognized by the compiler, as in a declaration such as the following. <lang Ursala>n = 724</lang> Signed rational numbers of unlimited precision are also a primitive type and can be expressed in conventional decimal form. <lang Ursala>m = -2/3</lang> The forward slash in a rational literal is only syntactic sugar and not interpreted as division, nor is the minus sign a general purpose negation operator. (A rational is stored as triple with a distinct sign, numerator, and denominator.)