php mac to int
Php mac to int
Generate randomized, strong, secure passwords.
Convert IPv4 CIDR notation.
Convert IPv6 CIDR notation.
Convert a mac address between integer, hexadecimal, dot notation and more
Convert IP addresses to decimal format, integer format, and more!
Convert between unix timestamp and datetime formats.
MAC Address Converter
Convert a mac address between integer, hexadecimal, dot notation and more!
EUI-48
EUI-64
Other Info
Media Access Control (MAC) address
Identifier given to a network interface that has been attached to a physical network segment. Each network interface has a unique MAC address. These addresses are used in many modern technologies, such as Ethernet and WiFi.
Notation conventions for MAC addresses vary, most of which are covered within this tool. The most common notations are hexadecimal notation and bit-reversed notation, both of which format the MAC address in 6 groups of 2 hexadecimal digits.
EUI-48
IEEE global identifier standard that is associated with 48-bit MAC addresses. These identifiers consist of 24-bits for the organization identifier, and 24-bits for the extension identifier. EUI-48 replaces the older term «MAC-48».
EUI-64
IEEE global identifier standard associated with 64-bit MAC addresses. These identifiers consist of 24-bits for the organization identifier, and 40-bits for the extension identifier.
Cast string to integer in PHP
I’ve been trying to convert string to int in PHP to operate on it, but PHP keeps interpreting it as 0.
I have tried several ways like
But they all give me 0 instead of 89.
How should this be done?
6 Answers 6
The easiest way to convert a string to a number:-
If you are still getting a zero there might be some odd, invisible chars in front of the number. To test for that :-
You can convert string to integer in two ways:
The code below removes the non numeric characters::
or remove double brackets too (for safe)
EDITED
will be good to remove all non numeric values:
and then convert to integer.
I had the same mistake. Indeed when i did var_dump($myvar). it returns string(2) «89» and when i did all the casts fonctions it returned me 0. I search and finally the answer is in this page. So I share with you what i learned. You have just to do a regex php : $myvar = preg_replace(«/[^0-9,.]»,»»,$myvar). It removes all the not number in your string (in my case the string(2)).
dechex
(PHP 4, PHP 5, PHP 7, PHP 8)
dechex — Decimal to hexadecimal
Description
Returns a string containing a hexadecimal representation of the given unsigned num argument.
Parameters
The decimal value to convert.
As PHP’s int type is signed, but dechex() deals with unsigned integers, negative integers will be treated as though they were unsigned.
Return Values
Examples
Example #1 dechex() example
The above example will output:
Example #2 dechex() example with large integers
The above example will output:
See Also
User Contributed Notes 33 notes
Be very careful calling dechex on a number if it’s stored in a string.
The max number it can handle is 4294967295 which in hex is FFFFFFFF, as it says in the documentation.
dechex(4294967295) => FFFFFFFF //CORRECT
BUT, if you call it on a string of a number, it casts to int, and automatically gives you the largest int it can handle.
dechex(‘4294967295’) => 7FFFFFFF //WRONG!
so you’ll need to cast to a float:
dechex((float) ‘4294967295’) => FFFFFFFF //CORRECT
This took me FOREVER to figure out, so hopefully I just saved someone some time.
Here are two functions that will convert large dec numbers to hex and vice versa. And I really mean LARGE, much larger than any function posted earlier.
now, here is a nice and small function to convert integers to hex strings and it avoids use of the DECHEX funtion because that function changed it’s behavior too often in the past (now, in PHP version 4.3.2 it works with numbers bigger than 0x7FFFFFFF correctly, but i need to be backward compatible).
Here is a very small zeropadding that you can use for numbers:
I was confused by dechex’s size limitation. Here is my solution to the problem. It supports much bigger values, as well as signs.
Easiest 😛 way to create random hex color:
Create Random Hex Color:
function rand_hex() <
mt_srand(make_seed());
$randval = mt_rand(0,255);
//convert to hex
return sprintf(«%02X»,$randval);
>
function random_color() <
return «#».rand_hex().rand_hex().rand_hex();
>
Here’s how to use bitwise operations for RGB2hex conversion. This function returns hexadesimal rgb value just like one submitted by gurke@bigfoot.com above.
function hexColor($color) <
return dechex(($color[0]
If you need to convert a large number (> PHP_MAX_INT) to a hex value, simply use base_convert. For example:
base_convert(‘2190964402’, 10, 16); // 829776b2
warning jbleau dec_to_hex method is buggy, avoid it.
I wrote this to convert hex into signed int, hope this helps someone out there. peace 🙂
If you want to create or parse signed Hex values:
I was challenged by a problem with large number calculations and conversion to hex within php. The calculation exceeded unsigned integer and even float range. You can easily change it for your needs but it is, thanks to bcmath, capable of handling big numbers via string. This function will convert them to hex.
In this specific example though, since I use it for game internals that can only handle 32 bit numbers, it will truncate calculations at 8 digits. If the input is 1 for example it will be filled up with zeros. Output 00000001h.
Of course I don’t claim it to be a good one, but it works for me and my purpose. Suggestions on faster code welcome!
To force the correct usage of 32-bit unsigned integer in some functions, just add ‘+0’ just before processing them.
These are functions to convert roman numbers (e.g. MXC) into dec and vice versa.
Note: romdec() does not check whether a string is really roman or not. To force a user-input into a real roman number use decrom(romdec($input)). This will turn XXXX into XL for example.
echo decrom ( romdec ( «XXXX» ));
?>
Warning for use on 64 bit machines! The Extra length matters!
so far it is ok. But for slightly bigger numbers:
note the difference!
This is particularly important when converting negative numbers:
If you want your code to be portable to amd64 or xeons (which are now quite popular with hosting companies) then you must ensure that your code copes with the different length of the result for negative numbers (and the max value, although that is probably less critical).
This function will take a string and convert it into a hexdump.
3c666f6e 74207369 7a653d22 33223e4c L
6561726e 20686f77 20746f20 62652061 earn.how.to.be.a
Here’s my version of a red->yellow->green gradient:
Here’s a function which works for decimal values up to 9007199254740992 (hex 20000000000000).
Heres a example of dec to html hex gradient. Have fun 🙂
//Amount of gradients
$l = 20;
//Start color
$start[0] = «255»; //red
$start[1] = «0»; //green
$start[2] = «255»; //blue
//End color
$end[0] = «255»; //red
$end[1] = «255»; //green
$end[2] = «255»; //blue
$rgb[$i] = dechex($rgb[$i]);
$rgb[$i] = strtoupper($rgb[$i]);
/*
here are two functions, some might find them useful (maybe for encoding)
converting string to hex and hex to string:
*/
Целые числа
Синтаксис
Целые числа могут быть указаны в десятичной (основание 10), шестнадцатеричной (основание 16), восьмеричной (основание 8) или двоичной (основание 2) системе счисления, с необязательным предшествующим знаком (- или +).
Двоичная запись integer доступна начиная с PHP 5.4.0.
Для записи в восьмеричной системе счисления, необходимо поставить пред числом 0 (ноль). Для записи в шестнадцатеричной системе счисления, необходимо поставить перед числом 0x. Для записи в двоичной системе счисления, необходимо поставить перед числом 0b
Пример #1 Целые числа
Формально, структуру целых чисел можно записать так:
Если в восьмеричном integer будет обнаружена неверная цифра (например, 8 или 9), оставшаяся часть числа будет проигнорирована.
Пример #2 Странности с восьмеричными числами
Переполнение целых чисел
Пример #3 Переполнение целых на 32-битных системах
Пример #4 Переполнение целых на 64-битных системах
Преобразование в целое
Из булевого типа
Из чисел с плавающей точкой
Если число с плавающей точкой превышает размеры integer (обычно +/- 2.15e+9 = 2^31 на 32-битных системах и +/- 9.22e+18 = 2^63 на 64-битных системах, кроме Windows), результат будет неопределенным, так как float не имеет достаточной точности, чтобы вернуть верный результат. В этом случае не будет выведено ни предупреждения, ни даже замечания!
Как преобразовать строку в число в PHP?
29 ответов:
обычно вам не нужно этого делать, так как PHP будет принуждать тип для вас в большинстве случаев. Для ситуаций, когда вы хотите явно преобразовать тип,cast это:
есть несколько способов сделать это:
приведите строки к числовым примитивным типам данных:
выполнение математических операций над строками:
на любом (слабо типизированном) языке вы всегда можете привести строку к числу, добавив к ней ноль.
однако, в этом очень мало смысла, так как PHP будет делать это автоматически во время использования этой переменной, и он будет приведен к строке в любом случае во время вывода.
обратите внимание, что вы можете сохранить пунктирные числа в виде строк, потому что после приведения к плаванию он может быть изменен непредсказуемо, из-за природы чисел с плавающей точкой.
или вы можете использовать:
немного грязно, но это работает.
можно использовать (int)_value_ например.
In PHP можно использовать intval(string) or floatval(string) функции для преобразования строк в числа.
вы всегда можете добавить ноль к нему!
просто небольшое примечание к ответам, которые могут быть полезны и безопаснее в некоторых случаях. Вы можете сначала проверить, действительно ли строка содержит допустимое числовое значение, а затем преобразовать его в числовой тип (например, если вам нужно манипулировать данными, поступающими из БД, которая преобразует ints в строки). Вы можете использовать is_numeric() а то floatval() :
Я обнаружил, что в JavaScript простой способ преобразовать строку в число, чтобы умножить его на 1. Он решает проблему конкатенации, потому что символ » + «имеет несколько применений в JavaScript, в то время как символ» * » предназначен исключительно для математического умножения.
основываясь на том, что я видел здесь в отношении PHP, автоматически готов интерпретировать строку, содержащую цифры, как число (и комментарии о добавлении, поскольку в PHP » + » является чисто математическим добавлением), этот трюк с умножением отлично работает и для PHP.
Я проверил его, и он действительно работает. Хотя в зависимости от того, как вы приобрели строку, вы можете применить к ней функцию trim (), прежде чем умножать на 1.
вот функция, которую я написал, чтобы упростить вещи для себя:
Он также возвращает сокращенные версии boolean, integer, double и real.
вызывая тип с parseNumeric установленным в true преобразует числовые строки перед проверкой типа.
Тип («5», true) вернет int
тип («3.7», true) вернет float
тип(«500») вернет строку
только будьте осторожны, так как это своего рода метод ложной проверки, и ваша фактическая переменная все равно будет строкой. Вам нужно будет преобразовать фактическую переменную в правильный тип, если это необходимо. Мне просто нужно было проверить, должна ли база данных загружать идентификатор элемента или псевдоним, таким образом, не имея никаких неожиданных эффектов, так как он будет проанализирован как строка во время выполнения в любом случае.
Edit
Если вы хотите определить, являются ли объекты функциями, добавьте этот случай к коммутатору:
кроме Boykodev ответ я предлагаю следующее:
вы можете использовать это для преобразования строки в int в PHP.
но лучшим решением является использование:
попробуйте использовать что-то вроде этого:
вы можете изменить тип данных следующим образом
по историческим причинам «double» возвращается в случае float.
для вашего конкретного случая вы можете просто умножить на 1, чтобы преобразовать строку в число в php. PHP заботится о плавающей и целочисленной автоматически.
PHP сделает это за вас в пределах