Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP convert byte string into integer

Tags:

php

byte

unpack

I am trying to convert a 2 byte string into a Short/int data type with unpack but it does not seem to work:

$str = "\x01\xBB";
unpack("S",$str);

it gives 47873 where as it must return 443

like image 703
asim-ishaq Avatar asked Sep 06 '14 21:09

asim-ishaq


People also ask

How to convert string into integer in PHP?

The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure. echo number_format( $num , 2);

How to create integer in PHP?

The (int), (integer), or intval() function are often used to convert a value to an integer.

How check if string is integer PHP?

The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.

How do I cast a string in PHP?

Answer: Use the strval() Function You can simply use type casting or the strval() function to convert an integer to a string in PHP.


1 Answers

You need to use n as the format string instead.

$str = "\x01\xBB";
unpack("n",$str);

Look here for more format options.
http://php.net/manual/en/function.pack.php

like image 200
ElefantPhace Avatar answered Sep 16 '22 12:09

ElefantPhace