Read a file in hex/bin/dec format with PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Read a file in hex/bin/dec format with PHP

Post by Oren »

Is there some PHP function which I don't know which reads a file but returns it as hex/bin/dec and not as a string?

I'll clarify. Say I use this function to read a .gif image (which starts with "GIF" - like any valid .gif image) and I do:

Code: Select all

$data = this_secret_func_which_idk('my_image.gif'); // let's say it returns the data in hex format
echo $data{0}; // prints '47' since 'G' = 0x47
All I really want is a way to read file (from any type) byte by byte, or even bit after bit if possible.

P.S I'm working on something very cool and if I ever manage to finish it, a lot of PHP programmers will thank me 8)

Edit: I see this is my 1111 post :P
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

Code: Select all

$bytes = file_get_contents(zzz);
$ints = unpack("c*", $bytes);
$hex = array_map('dechex', $ints);
echo $hex[0]; // 47
see pack, unpack, ord, chr, dechex, sprintf and others ;)
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

Thanks man. I still need to test it and play with it, but it seems to be working.

P.S If you have other ways to do this I'm listening...

Edit: By the way... it needs to be: $hex[1] instead of: $hex[0]
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Why must it be a one-based array?
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

I guess this is how unpack() works... I have no idea.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I misread your post. I thought you were referring to a need in your program for a one-based array, not that unpack() was returning a one-based array.
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

Some of the elements in the result array are padded with f's (e.g a byte holds the value: 0xD0, it shows as: 'ffffffd0'). Why?

Thanks guys :P
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

C'mon guys... anyone? I'm working on something that may help a lot of people here 8)
Post Reply