cc: [email protected] 
Subject: Re: [ast-users] ksh read byte
--------

> The builtin manual of ksh's "read" says:
>    "-N nbyte   Read exactly nsize characters.
>                For binary fields size will be in bytes."
> 
> I've tried to read single bytes with "read -N1".  The following, using 
> "od", works as expected and thus confirms that "read -N1" is working:
> 
>    #!/bin/ksh
> 
>    exec 3< hexfile   ## file of 256 bytes: 0, 1, 2, 3, ... 255
> 
>    while read -u3 -r -N1 B
>    do
>      H=$(printf "$B" | od -tx1 -An)
>      print ${H:=" 00"}
>    done | less
> 
>    exec 3<&-
> 
> But I want to compare $B to constant values, and print $B as ascii-hex, 
> and I'd like to avoid using external application "od".  If I declare B 
> with "typeset -is", or "typeset -i", or "typeset -b", the result is 
> "arithmetic syntax error" or nonsense.  Behavior is the same for locale 
> "C" and "en_ZA.utf8".  Of course it can be done (ksh can do anything!) 
> but please tell me, "How?".
> 
> 

Assuming that the data you read in is a valid character in that locale,
I would expect that in the C locale
        exec 3< hexfile   ## file of 256 bytes: 1, 2, 3, ... 127
        while read -u3 -r -N1 B
        do      print -r -- $(('$B'))
        done | less
        exec 3<&-

would work.  However, for 0 or a character not in the current locale,
this will not work.  read return the Empty string for the 0 byte.

You could use
        printf "%d\n" "'$B'"
instead and shorten it to

        while read -u3 -r -N1 B
        do      printf "%d\n" ${B+"'$B'"}
        done < hexfile | less

which also handles 0.

read will return 1 for an invalid character.


David Korn
[email protected]
_______________________________________________
ast-users mailing list
[email protected]
https://mailman.research.att.com/mailman/listinfo/ast-users

Reply via email to