PHP - 读取8位整数

发布于 2024-11-03 20:14:28 字数 379 浏览 3 评论 0原文

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

$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);

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

避讳 2024-11-10 20:14:28

您要寻找的是 char 数据类型。现在有两个版本,有符号(小写c)和无符号(大写C)。只需使用适合您的数据的那个即可。

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

另外,如果数据文件只是一堆字节而没有其他内容,并且您知道它的长度,则可以执行此操作。 (如果长度是连续 16 个有符号字符。)

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

如果您不知道文件中有多少字节,但您知道只有字节,您可以使用星号代码读取直到 EOF。

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

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);
?>
醉殇 2024-11-10 20:14:28

以下应该执行您想要的操作(ord):

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

您想要做的是检索单个字节的整数值。因为您一次读取单个字节,所以您将始终只有一个有效的 ASCII 字符。 ord 返回该字符的二进制值。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文