[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: OT: Some advice on perl: read byte to hex string



On 09/21/2006 12:06 AM, Welly Hartanto wrote:
Thank you for all your suggestions.
It's solved by using :

for ($i=0; $i < (length($gotit)); $i++) {
    my $c = substr($gotit, $i, 1);
    $str1 = sprintf("%01x", ((ord($c) & 0xf0) >> 4) & 0x0f);
    $str2 = sprintf("%01x", ord($c) & 0x0f);
    print $str1.$str2."\t";
    print "\n";
}

At least for converting the data.
But another problem is it's only show the first 8 bytes only.

The code you posted decodes all of the data.

The data sent from the device is 11 bytes, so now 3 bytes are
missing.
I think it's something about the buffer (?)

::welly hartanto::

Below is the flow on how to read the data :

The thing is the data sometimes will form in a negative byte.
That's why some bitwise and AND operation exist.
To produce the right output I should :
1. Seperate the first 4 bit ( with & 0xF0 and 4 bitwise) .
2. And get the value back with & 0x0F.
3. Store the value ( name it "first").
4. The rest 4 bit with the & 0x0F.
5. Store the value as "second".
6. Make both value formed as hex string then concate them as firstsecond.


There is no need to write assembly-language-level code in Perl. Perl's "unpack" function (perldoc -f pack) does all of this much more quickly and cleanly than you could.

For example, the first byte which will be sent from the card reader device
will always 01111110(bin), which is 126(dec) or 7E(hex).

1. The & 0xF0
    01111110    <--- original value
    11110000
    -------- &
    01110000

2. The >> 4
    01110000 >> 4 = 00000111

3. The & 0xF0
    00000111
    00001111
    -------- &
    00000111


Nope, That is operation is and-ing with 0x0F.

4. The value is 7(dec) and 7(hex)
5. The last 4bit with & 0xF0

    01111110
    00001111
    -------- &
    00001110

6. The value is 14(dec) or E(hex)
7. So the result will be 7E ( after concate with the first value ).




In a terminal, type "perldoc -f pack"; there's no need for silly mathematical mistakes to trip you up; just use unpack. Try this and see what happens:

    my $hex = unpack 'H*', $gotit;
    $hex = join ' ', $hex =~ /../g;
    print $hex, "\n";

--
paduille.4058.mumia.w@earthlink.net



Reply to: