...

View Full Version : PHP to read a file and print the value as Decimal



jmknash
01-16-2012, 09:29 PM
Hello,

I would like a script to read a text file containing a single ASCII character and print it out on a webpage as it's Decimal value. I cannot find such script anywhere and know few of PHP coding to modify the below code.

Below is a script I found which prints as Hexadecimal.

<?php

$handle = @fopen("DATA.TXT", "r");
if ($handle) {
while (!feof($handle)) {
$hex = bin2hex(fread ($handle , 4 ));
print $hex."\n";
}
fclose($handle);

}

?>



` DATA.txt contains:
t

Any help appreciated. Thanks, Jon.

Fou-Lu
01-16-2012, 09:57 PM
I assume you don't mean 'decimal' then, since there is no floating point representation for an ascii character. Use the ord() function to pull the hex representation of the character instead. If you want to convert to an integer, you can use base_convert to change the base from 16 to 10.

mlseim
01-16-2012, 09:58 PM
$data=file("DATA.TXT");
echo ascii_to_dec($data[0]);

Fou-Lu
01-16-2012, 10:16 PM
$data=file("DATA.TXT");
echo ascii_to_dec($data[0]);


O.o
There's no ascii_to_dec function in PHP :P


Oh that does remind me though. I needed to verify the base returned by ord, and its actually base 10, not base 16. So an ord('t') will be 116, not 0x74 (which yes is the exact same thing). Since ord doesn't return a string, no conversion is necessary.

jmknash
01-16-2012, 10:25 PM
Fou-Lu, so converting the hex to decimal?...

mlseim, unfortunately your code resulted in errors

Fou-Lu
01-17-2012, 01:29 PM
Fou-Lu, so converting the hex to decimal?...

mlseim, unfortunately your code resulted in errors

Its already an integer. Making a decimal doesn't make any sense since there is no fractions in ascii. If for whatever reason you want it that way you can cast it to a float.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum