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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to define a binary number

Status
Not open for further replies.

charlie007

Programmer
Jul 14, 2004
8
US
I can not figure out how to define a hex number 80
I'm using this:
set hexb [binary format H* 80]

I am sending $hexb as part of a string to serial port (see program below). I put on serial port monitor and see 3F as the data. Don't know why 80 is not being sent, yet [format %2X [scan $hexb %c]] displays 80.

If I use
set hexb [binary format H* 81]
hex 81 is sent OK.

Also tried:
set hexb [binary format B* 10000000]
with same results (0x3F)
Please help.

if { [catch {set comport5 [open "com5" "r+"]} fid] } {
set ans [tk_messageBox -message "com5-$fid" -title "OPEN ERROR" -type ok -icon question]
exit
}
fconfigure $comport5 -mode "14400,n,8,1"
set hexa [binary format H* 63]
set hexb [binary format H* 80]
set hexc [binary format H* 63]
set hexd [binary format H* 81]
while {0==0} {
set ans [tk_messageBox -message "yes=0x[format %2X [scan $hexa %c]] 0x[format %2X [scan $hexb %c]] no=0x[format %2X [scan $hexc %c]] 0x[format %2X [scan $hexd %c]] cancel=exit" -type yesnocancel -default yes -icon question -title "USB relay 1"]
switch -exact -- $ans {
yes {set c "x$hexa$hexb//"}
no {set c "x$hexc$hexd//"}
cancel {break}
}
puts -nonewline $comport5 $c
flush $comport5
}
close $comport5

exit
 
binary format and binary scan can be tricky and I try to avoid them when I can. Why not use format?
Code:
% format %x 80
50
% format %x 81
51

_________________
Bob Rashkin
 
That said, I guess I'm not sure what you're trying to do. Here are some procs that deal with binary numbers:
Code:
#Hex string to decimal integer
proc hxB2decN {hnm} {
    set ln [string length $hnm]
    if $ln!=2 then {return "input must be 1 byte"}
    set y1 [binary format H2 $hnm]
    binary scan $y1 c* y2
    set y2 [expr {($y2 + 0x100 ) % 0x100}]
    return $y2
}
#decimal integer to Hex string
proc decN2Hx {dn} {
     if $dn>255 then {return "input must be 1 byte"}
     binary scan [binary format c $dn] H2 hc
     return $hc
}
#hex string to binary string
proc Ahx2Abn {hx} {
     if {[string length $hx] != 4} then {return "input must be 4 hex char's"}
     binary scan [binary format H4 $hx] B16 bc
     return $bc
}

_________________
Bob Rashkin
 
Nevermind, figured it out. Needed -translation {binary binary} on fconfigure.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top