Bash - binary data to ascii code

Hello,

With bash-script (ubunto server) I'm trying to read a binary file and, for each character, give back its ascii code (including extended ascii). For example:

HEX => ASCII => PRINT
f5 => 245 => �
50 => 80 => P

To load the binary file into a variable I tried in this way:

s=$(<"binaryfile.bin") 

and for finding its length:

n=${#s} 

However, $s does not seem to correspond to the actual content of the file and therefore also the length.

The exact number of characters I get in fact doing:

n=$(stat c%s "binaryfile.bin")

What I do not get is $s to match character for character the content of BinaryFile.

The equivalent vb6 works this way:

Open DataFile For Binary As #1 
s = Input (LOF (1), 1) 
n = len(s)
Close 1 

For i = 1 To n
sn(i) = Asc(Mid(s, i, 1))
Next

I also tried to work with hexdump ...

hexdump -C binaryfile.bin 

but I can not print the ascii code (extended) characters in the file.

If the variable $s contain the exact text of the file, I could use the following functions to get each character its ascii code (which is what I need).

<cut>
 for(( i=0; i<=n; i++))
 do
    one_char=${s:i:1}
    sn[$i]=$(ord "$one_char");
 done
<cut>

#Asc() function
ord() {
  LC_CTYPE=C printf '%d' "'$1"
}

#Chr() function
chr() {
  [ "${1}" -lt 256 ] || return 1
  printf \\$(printf '%03o' $1)
}

Any help?

Thank you
math

This request is locale dependent, e.g. in UTF-8 the "�" char is not 245, but the 16 bit representation 195 182. So watch out!

One solution to your problem might be the use of od :

cat file
Padventure
�adventures
Padv��ersary
od -An -tu1 file
  80  97 100 118 101 110 116 117 114 101  10 195 182  97 100 118
 101 110 116 117 114 101 115  10  80  97 100 118 195 150 195 188
 101 114 115  97 114 121  10
1 Like

:eek: There have been over TWO days (h24) to no avail.

I also saw the OD command but I was lost.
I am new to UNIX and I am converting some domestic services that I had done in windows.

It's perfect, thank you RudiC.
Math