Welcome, guest | Sign In | My Account | Store | Cart

Two procedures from the bag of utilities used by Jeff Hobbs. The first computes the largest integer supported by Tcl on the platform it is run on. The second computes the number of bits in that integer.

Tcl, 28 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# largest_int --
#   Finds the largest recognized int in Tcl for the platform
# Arguments:
#   none
# Results:
#   Returns the largest allowed value for an int (for exprs and stuff)
#
proc largest_int {} {
    set int 1
    set exp 7; # assume we get at least 8 bits
    while {$int > 0} { set int [expr {1 << [incr exp]}] }
    expr {$int-1}
}

# int_bits --
#   Finds the number of bits in an int
# Arguments:
#   none
# Results:
#   Returns the numbers of bits in an int
#
proc int_bits {} {
    set int 1
    set exp 7; # assume we get at least 8 bits
    while {$int > 0} { set int [expr {1 << [incr exp]}] }
    # pop up one more, since we start at 0
    incr exp
}

1 comment

Keith Vetter 18 years, 7 months ago  # | flag

For most modern computers, the following one-liners also work:

LARGEST INT:   expr {[regsub F [format "0x%X" -1] 7]}
BITS PER INT:  expr {4 * [string length [format %X -1]]}

You need tcl 8.4 for the first one.

Created by andreas kupries on Wed, 21 Aug 2002 (MIT)
Tcl recipes (162)
andreas kupries's recipes (20)

Required Modules

  • (none specified)

Other Information and Tasks