Bytes аналог в php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Reading And Writing Binary Data (incl. primitive types, ex. byte, ubyte, short, ushort, int, uint, long, float, double). The classes also help with porting the I/O operations of the JAVA code.

Ne-Lexa/php-byte-buffer

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

nelexa/buffer -> Read And Write Binary Data

This is classes defines methods for reading and writing values of all primitive types. Primitive values are translated to (or from) sequences of bytes according to the buffer’s current byte order, which may be retrieved and modified via the order methods. The initial order of a byte buffer is always Buffer::BIG_ENDIAN.

composer require nelexa/buffer

Class \Nelexa\Buffer is abstract and base methods for all other buffers.

Initialize buffer as string.

$buffer = new \Nelexa\StringBuffer(); // or $buffer = new \Nelexa\StringBuffer($text);

Initialize buffer as file.

$buffer = new \Nelexa\FileBuffer($filename);

Initialize buffer as memory resource (php://memory).

$buffer = new \Nelexa\MemoryReourceBuffer(); // or $buffer = new \Nelexa\MemoryReourceBuffer($text);

Initialize buffer as stream resource.

$fp = fopen('php://temp', 'w+b'); // or $buffer = new \Nelexa\ResourceBuffer($fp);

Checking the possibility of recording in the buffer

$boolValue = $buffer->isReadOnly();

Modifies this buffer’s byte order, either Buffer::BIG_ENDIAN or Buffer::LITTLE_ENDIAN

$buffer->setOrder(\Nelexa\Buffer::LITTLE_ENDIAN);
$buffer->setPosition($position);
$buffer->skip($count); // example $buffer->insertString('Test value'); assert($buffer->position() === 10); $buffer->skip(-7); assert($buffer->position() === 3); $buffer->skip(2); assert($buffer->position() === 5);
$buffer->skipByte(); // skip 1 byte $buffer->skipShort(); // skip 2 bytes $buffer->skipInt(); // skip 4 bytes $buffer->skipLong(); // skip 8 bytes $buffer->skipFloat(); // skip 4 bytes $buffer->skipDouble(); // skip 8 bytes

Rewinds this buffer. The position is set to zero.

$buffer->rewind(); // example $buffer->insertString('Test value'); assert($buffer->position() === 10); $buffer->rewind(); assert($buffer->position() === 0); assert($buffer->size() === 10);

Flips this buffer. The limit is set to the current position and then the position is set to zero.

$buffer->flip(); // example $buffer->insertString('Test value'); assert($buffer->position() === 10); $buffer->setPosition(5); $buffer->flip(); assert($buffer->position() === 0); assert($buffer->size() === 5);

Returns the number of elements between the current position and the limit.

$remaining = $buffer->remaining(); // example $buffer->insertString('Test value'); assert($buffer->position() === 10); $buffer->setPosition(7); assert($buffer->remaining() === 10 - 7);

Tells whether there are any elements between the current position and the limit. True if, and only if, there is at least one element remaining in this buffer

$boolValue = $buffer->hasRemaining(); // example $buffer->insertString('Test value'); assert($buffer->position() === 10); assert($buffer->hasRemaining() === false); $buffer->setPosition(9); assert($buffer->hasRemaining() === true);

Close buffer and release resources

Читайте также:  Расположение элементов внутри div css

Read the entire contents of the buffer into a string without changing the position of the buffer.

$allBufferContent = $buffer->toString(); // example $buffer->insertString('Test value'); assert($buffer->position() === 10); $buffer->setPosition(4); $allBufferContent = $buffer->toString(); assert($buffer->position() === 4); assert($allBufferContent === 'Test value');

Reads the string at this buffer’s current position, and then increments the position.

$content = $buffer->get($length); // example $buffer->insertString('Test value'); assert($buffer->position() === 10); $buffer->setPosition(3); $content = $buffer->get(5); assert($buffer->position() === 8); assert($content === 't val');
Method Type Values
$buffer->getBoolean boolean true or false
$buffer->getByte() byte -128 . 127
$buffer->getUnsignedByte() unsigned byte (ubyte) 0 . 255
$buffer->getShort() short (2 bytes) -32768 . 32767
$buffer->getUnsignedShort() unsigned short (ushort) 0 . 65535
$buffer->getInt() int (4 bytes) -2147483648 . 2147483647
$buffer->getUnsignedInt() unsigned int (uint) 0 . 4294967296
$buffer->getLong() long (8 bytes) -9223372036854775808 . 9223372036854775807
$buffer->getFloat() float (4 bytes) single-precision 32-bit IEEE 754 floating point number
$buffer->getDouble() double (5 bytes) double-precision 64-bit IEEE 754 floating point number
$buffer->getArrayBytes($length) byte[] array
$buffer->getString($length) string (length bytes) string
$buffer->getUTF() string string
$buffer->getUTF16($length) string (length * 2) string

Insert string (byte[]) or Buffer to buffer.

$buffer->insert('content'); // or $buffer->insert(new StringBuffer('Other buffer')); // example assert($buffer->position() === 0); assert($buffer->size() === 0); $buffer->insert('Test value'); assert($buffer->position() === 10); assert($buffer->size() === 10); $buffer->setPosition(4); $buffer->insert('ed'); assert($buffer->position() === 6); assert($buffer->size() === 12); assert($buffer->toString() === 'Tested value');

Insert boolean value false or true . Change size and position by +1.

$buffer->insertBoolean($boolValue);
$buffer->insertByte($byteValue);

Источник

Читайте также:  Python use command line args

Строка в байтовый массив в php

Как я могу получить массив байтов из некоторой строки, которая может содержать числа, буквы и т. Д.? Если вы знакомы с Java, я ищу ту же функциональность метода getBytes ().

Я попробовал такой сниппет:

но безуспешно, поэтому любая помощь будет оценена по достоинству.

PS: Зачем мне это вообще ?? Ну, мне нужно отправить массив байтов через fputs () на сервер, написанный на Java …

@Sparr прав, но я предполагаю, что вы ожидали массив byte[] например byte[] в C #. Это то же самое решение, что и Sparr, но вместо HEX вы ожидали int presentation ( диапазон от 0 до 255 ) каждого char . Вы можете сделать следующее:

$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog'); var_dump($byte_array); // $byte_array should be int[] which can be converted // to byte[] in C# since values are range of 0 - 255 

Используя var_dump вы можете видеть, что элементы являются int ( not string ).

 array(44) < [1]=>int(84) [2]=> int(104) [3]=> int(101) [4]=> int(32) [5]=> int(113) [6]=> int(117) [7]=> int(105) [8]=> int(99) [9]=> int(107) [10]=> int(32) [11]=> int(102) [12]=> int(111) [13]=> int(120) [14]=> int(32) [15]=> int(106) [16]=> int(117) [17]=> int(109) [18]=> int(112) [19]=> int(101) [20]=> int(100) [21]=> int(32) [22]=> int(111) [23]=> int(118) [24]=> int(101) [25]=> int(114) [26]=> int(32) [27]=> int(116) [28]=> int(104) [29]=> int(101) [30]=> int(32) [31]=> int(108) [32]=> int(97) [33]=> int(122) [34]=> int(121) [35]=> int(32) [36]=> int(98) [37]=> int(114) [38]=> int(111) [39]=> int(119) [40]=> int(110) [41]=> int(32) [42]=> int(100) [43]=> int(111) [44]=> int(103) > 
print_r(unpack("H*","The quick fox jumped over the lazy brown dog")) Array ( [1] => 54686520717569636b20666f78206a756d706564206f76657220746865206c617a792062726f776e20646f67 ) 

При необходимости вы можете разделить результат на два столбца с шестнадцатеричным символом.

Вы можете попробовать следующее:

$in_str = 'this is a test'; $hex_ary = array(); foreach (str_split($in_str) as $chr) < $hex_ary[] = sprintf("%02X", ord($chr)); >echo implode(' ',$hex_ary); 

В PHP строки – это потоки. Что именно ты пытаешься сделать?

Ps. Зачем мне это вообще ?? Ну, мне нужно отправить через fputs () bytearray на сервер, написанный в java …

fputs принимает строку в качестве аргумента. Скорее всего, вам просто нужно передать свою строку. На стороне Java вещи вы должны декодировать данные в любой кодировке, которую вы используете в php (по умолчанию iso-8859-1).

PHP не имеет явного типа byte , но его string уже является эквивалентом массива байтов Java. Вы можете безопасно писать fputs($connection, «The quick brown fox …») . Единственное, что вы должны знать, это кодирование символов, они должны быть одинаковыми с обеих сторон. Используйте mb_convert_encoding (), когда вы сомневаетесь.

Читайте также:  Java google oauth2 example

Я нашел несколько функций, определенных в http://tw1.php.net/unpack , очень полезными.
Они могут скрывать строку в байтовый массив и наоборот.

Возьмите byteStr2byteArray () в качестве примера:

 $msg = "abcdefghijk"; $byte_array = byteStr2byteArray($msg); for($i=0;$i ?> 

Источник

How to Get the Byte Values of a String in PHP

How can I get the single bytes from a multibyte PHP string variable in a binary-safe way?

you can get a bytearray by unpacking the utf8_encoded string $a:

$a = utf8_encode('Fön');
$b = unpack('C*', $a);
var_dump($b);

used format C* for «unsigned char»

  • String to byte array in php
  • http://www.php.net/manual/en/function.unpack.php
  • http://www.php.net/manual/en/function.pack.php

String to byte array in php

@Sparr is right, but I guess you expected byte array like byte[] in C#. It’s the same solution as Sparr did but instead of HEX you expected int presentation (range from 0 to 255) of each char . You can do as follows:

$byte_array = unpack('C*', 'The quick fox jumped over the lazy brown dog');
var_dump($byte_array); // $byte_array should be int[] which can be converted
// to byte[] in C# since values are range of 0 - 255

By using var_dump you can see that elements are int (not string ).

 array(44) < [1]=>int(84) [2]=> int(104) [3]=> int(101) [4]=> int(32)
[5]=> int(113) [6]=> int(117) [7]=> int(105) [8]=> int(99) [9]=> int(107)
[10]=> int(32) [11]=> int(102) [12]=> int(111) [13]=> int(120) [14]=> int(32)
[15]=> int(106) [16]=> int(117) [17]=> int(109) [18]=> int(112) [19]=> int(101)
[20]=> int(100) [21]=> int(32) [22]=> int(111) [23]=> int(118) [24]=> int(101)
[25]=> int(114) [26]=> int(32) [27]=> int(116) [28]=> int(104) [29]=> int(101)
[30]=> int(32) [31]=> int(108) [32]=> int(97) [33]=> int(122) [34]=> int(121)
[35]=> int(32) [36]=> int(98) [37]=> int(114) [38]=> int(111) [39]=> int(119)
[40]=> int(110) [41]=> int(32) [42]=> int(100) [43]=> int(111) [44]=> int(103) >

Be careful: the output array is of 1-based index (as it was pointed out in the comment)

PHP Read Byte Range from String or File

You should be able to do this with fseek and fread .

$byteOffset = 1024;
$readLength = 256;
$fileHandle = fopen('myfile', 'r');
fseek($fileHandle, $byteOffset);
$bytes = fread($fileHandle, $readLength);

String to byte/binary arrays in PHP

I think you are asking for the equivalent to the Perl pack/unpack functions. If that is the case, I suggest you look at the PHP pack/unpack functions:

How can I convert array of bytes to a string in PHP?

If by array of bytes you mean:

$bytes = array(255, 0, 55, 42, 17, );

array_map()

$string = implode(array_map("chr", $bytes));

foreach()

Which is the compact version of:

$string = "";
foreach ($bytes as $chr) $string .= chr($chr);
>
// Might be a bit speedier due to not constructing a temporary array.

pack()

But the most advisable alternative could be to use pack(«C*», [$array. ]) , even though it requires a funky array workaround in PHP to pass the integer list:

$str = call_user_func_array("pack", array_merge(array("C*"), $bytes)));

That construct is also more useful if you might need to switch from bytes C* (for ASCII strings) to words S* (for UCS2) or even have a list of 32bit integers L* (e.g. a UCS4 Unicode string).

Источник

Оцените статью