PHP - 读取8位整数

问题描述:

I have a binary file that is all 8 bit integers. I have tried to use the php unpack() functions but I cant get any of the arguments to work for 1 byte integers. I have tried to combine the data with a dummy byte so that I can use the 'n'/'v' arguments. I am working with a windows machine to do this. Ultimately I would like a function to return an array of integers based on a string of 8 bit binary integers. The code I have tried is below -

$dat_handle = "intergers.dat";
$dat_file = fopen($dat_handle, "rb");
$dat_data = fread($dat_file, 1);
$dummy = decbin(0);
$combined = $dummy.$dat_data;
$result = unpack("n", $combined);

我有一个所有8位整数的二进制文件。 我曾尝试使用php unpack()函数,但我无法获得任何1个字节整数的参数。 我试图将数据与虚拟字节组合在一起,以便我可以使用'n'/'v'参数。 我正在使用Windows机器来执行此操作。 最后我想要一个函数来返回一个基于8位二进制整数字符串的整数数组。 我试过的代码如下 - p>

  $ dat_handle =“intergers.dat”; 
 $ dat_file = fopen($ dat_handle,“rb”); 
 $ dat_data  = fread($ dat_file,1); 
 $ dummy = decbin(0); 
 $ combined = $ dummy。$ dat_data; 
 $ result = unpack(“n”,$ combined); 
  code  >  pre> 
  div>

What your looking for is the char datatype. Now there are two version of this, signed (lowercase c) and unsigned (uppercase C). Just use the one that's correct for your data.

<?php
    $byte = unpack('c', $byte);
?>

Also, if the data file is just a bunch of bytes and nothing else, and you know it's length, you can do this. (If the length is 16 signed chars in a row.)

<?php
    $bytes = unpack('c16', $byte);
?>

If you don't know how many bytes will be in the file, but you know there is only going to be bytes you can use the asterisk code to read until EOF.

<?php
    $bytes = unpack('c*', $byte);
?>

The following should do what you want (ord):

$dat_handle = "intergers.dat";
$dat_file = fopen($dat_handle, "rb");
$dat_data = ord(fread($dat_file, 1));

What you are trying to do is retrieve the integer value of the single byte. Because you are reading in single bytes at a time, you will always have exactly one valid ASCII character. ord returns the binary value of that one character.