Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hexadecimal Conversion??? 1

Status
Not open for further replies.

shussai2

Programmer
Aug 28, 2003
42
0
0
CA
Hi guys,

Similar sort of question to the one I asked before (Binary Conversion). This time I was wondering how can I display a hexadecimal representation of a binary number or string.
For example, suppose I have a list of 8-bits:

set bitList "0 0 0 0 1 0 1 0"

By just examining it right now the hexadecimal representation is 0A.
But how would I convert this into the hexadecimal rep and display it on screen.

Please help me out again.

Regards
 
The Tcl'ers Wiki page "Binary representation of numbers," comes to the rescue again. There are a couple of bits2int and int2bits procedures presented there. Here are Richard Suchenwirth's:

Code:
proc int2bits {i} {
    #returns a bitslist, e.g. int2bits 10 => {1 0 1 0}
    set res ""
    while {$i>0} {
        set res [expr {$i%2}]$res
        set i [expr {$i/2}]
    }
    if {$res==""} {set res 0}
    split $res ""
}

proc bits2int {bits} {
    #returns integer equivalent of a bitlist
    set res 0
    foreach i $bits {
        set res [expr {$res*2+$i}]
    }
    set res
}

Once you've got an integer representation of the value, simply use format to format it in hexadecimal form:

[tt]% [ignore]set bitList {0 0 0 0 1 0 1 0}[/ignore]
0 0 0 0 1 0 1 0
% [ignore]set value [bits2int $bitList][/ignore]
10
% [ignore]puts [format "%x" $value][/ignore]
a
% [ignore]puts [format "%X" $value][/ignore]
A
% [ignore]puts [format "%2X" $value][/ignore]
A
% [ignore]puts [format "%02X" $value][/ignore]
0A
% [ignore]set bitList2 {0 0 1 0 1 1 1 0 0 0 1 0 1 1 1 0}[/ignore]
0 0 1 0 1 1 1 0 0 0 1 0 1 1 1 0
% [ignore]set value [bits2int $bitList2][/ignore]
11822
% [ignore]puts [format "%04X" $value][/ignore]
2E2E[/tt]

Alternatively, you cound omit the procedures and just use the binary format and binary scan commands:

[tt]% [ignore]binary scan [binary format B* [join $bitList2 ""]] H* x[/ignore]
1
% [ignore]puts $x[/ignore]
2e2e
% [ignore]set bitList2 {0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 1 1 0 1 0 0 0 1 0 0 1 1 0 0 1 0}[/ignore]
0 0 1 0 1 1 0 0 1 1 0 1 0 0 1 1 1 1 0 1 0 0 0 1 0 0 1 1 0 0 1 0
% [ignore]binary scan [binary format B* [join $bitList2 ""]] H* x[/ignore]
1
% [ignore]puts $x
2cd3d132[/tt]

- Ken Jones, President, ken@avia-training.com
Avia Training and Consulting, 866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top