PHP | gmp_setbit() Function

The gmp_setbit() function is an inbuilt function in PHP which is used to set the bit index in given $num.

Syntax:

void gmp_setbit( GMP $num, int $index, bool $bit_on )

Parameters: This function accepts three parameters as mentioned above and described below:



  • $num: It is a required parameter. This parameter gives the value to be modified. This parameter can be a GMP number resource in PHP 5.5 and earlier, a GMP object in PHP 5.6 and later, or we are also allowed to pass a numeric string provided that it is possible to convert that string to a number.
  • $index: It is a required parameter. This parameter provides the index to be set. Here index 0 represents the least significant bit.
  • $set_state: This parameter sets the bits, if “True” it sets the bit to 1/on and if “False”, it will clear the bit that is set the bit to 0/off.

Return Value: This function returns the GMP number resource in PHP 5.5 and earlier, or a GMP object in PHP 5.6 and later.

Program 1: Program to illustrate gmp_setbit() function having index 0:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to demonstrate the gmp_setbit() function
// with index 0
  
// It will create a gmp number
$num = gmp_init("2");  
  
// gmp_strval will return the string value of a GMP number
// when the argument is numeric string and 
// the second parameter is present 
echo gmp_strval($num), ' -> 0b', gmp_strval($num, 2), "\n"
  
gmp_setbit($num, 0);  // 0b10 now becomes 0b11
  
echo gmp_strval($num), ' -> 0b', gmp_strval($num, 2);
?>

chevron_right


Output:

2 -> 0b10
3 -> 0b11

Program 2: Program of gmp_setbit() function for clearing the bit:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// php program to illustrate gmp_setbit() function
// for clearing bit
  
// gmp_init() will create a gmp number
$num = gmp_init("3");
  
// gmp_strval will return the string value of a GMP number
// when the argument is numeric string and 
// the second parameter is present 
echo gmp_strval($num), ' -> 0b', gmp_strval($num, 2), "\n";
  
gmp_setbit($num, 0, false); // clearing bit at index 0
  
echo gmp_strval($num), ' -> 0b', gmp_strval($num, 2);
?>

chevron_right


Output :

3 -> 0b11
2 -> 0b10

Reference: http://php.net/manual/en/function.gmp-setbit.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai