Dave Carrigan wrote:
Thank you for all your suggestions.On Tuesday 19 September 2006 23:29, Welly Hartanto wrote:for ($i=0; $i < (length($gotit)); $i++) { my $c = substr($gotit, $i, 1); $c1 = $c & 0xF0; #get the high nibble $c1 = $c1 >> 4; # $c1 = $c1 & 0x0F; #$c is not a byte; it is a variable that contains a 1-byte string. So doing bitwise operations like & on it won't do what you expect. What it will do is convert $c to a numeric value (if possible) and then perform the &. For most of the data you are probably reading, it's converting it to 0 because it's not numeric to begin with. The rest of the time, it would convert it to some number between 1 and 9.Presumably, what you want is the value of the byte from 0 to 255. So, you first need to convert $c to that value using the ord function. $c1 = ((ord($c) & 0xf0) >> 4) & 0x0f;$str1 = hex($c1); #convert to hexI don't know what this hex function is supposed to do. Most likely, you want $str1 = sprintf("%02x", $c1);$c2 = $c & 0x0F; #get the low nibble $str2 = hec($c2); #convert to hex$str2 = sprintf("%02x", ord($c) & 0x0f); 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 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. 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 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 ). |
- Re: OT: Some advice on perl: read byte to hex string Welly Hartanto