s c h e m a t i c s : c o o k b o o k

/ WebHome / TOC / NumberChapter / Cookbook.NumberRecipeConvOctHex

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Converting Between Octal and Hexadecimal

Problem

You want to convert a string (e.g., "0x55" or "0755") containing an octal or hexadecimal number to the correct number.

Solution

Use the string->number and number->string built in functions.

> (string->number "55" 16)
85
> (string->number "0755" 8)
493

Discussion

The string->number function takes an optional radix (which must be an exact integer, either 2, 8, 10, or 16). If not supplied, it defaults to decimal unless an explicit radix is included in the number string. For example, "#o177" is octal, "#xff" is hexadecimal.

> (string->number "#o177")
127
> (string->number "#XFF")
255

Note that the radix and numbers may be upper or lower case.

Here's an example that accepts a number in either decimal, octal, or hex, and prints that number in all three bases. It uses the oct function to convert from octal and hexadecimal if the input began with a 0. It then uses printf to convert back into hex, octal, and decimal as needed.

(define (convert str)
  (let ((num (string->number str)))
    (printf "decimal=~a, hex=~a, octal=~a"
            (number->string num)
            (number->string num 16)
            (number->string num 8))))

> (convert "#o17")
decimal=15, hex=f, octal=17
> (convert "17")
decimal=17, hex=11, octal=21
> (convert "#X17")
decimal=23, hex=17, octal=27

The following code converts Unix file permissions. They're always given in octal, so we assume base 8:

(define (fp-convert str)
  (let ((perm (string->number str 8)))
    (printf "The decimal value is ~a~n" (number->string perm))))

> (fp-convert "777")
The decimal value is 511

See Also

NumberRecipesConvertBinDec

CookbookForm
TopicType: Recipe
ParentTopic: NumberRecipes
TopicOrder: 130

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest