Witam,
Jak w podanej przez użytkownika liczbie zamienic dwa wybrane(przez użytkownika) bity miejscami .
Jeśli chcesz edytować konkretne bity to najwygodniej będzie użyć std::bitset. Za pomocą operatora [] edytujesz konkretne bity jak tablicę. Na koniec wołasz to_ulong
albo to_ullong
i rzutujesz na wcześniejszy typ.
const int NUM = 10;
std::bitset<sizeof NUM> bits(NUM);
const bool tmp = bits[2];
bits[2] = bits[3];
bits[3] = tmp;
const int editedNum = static_cast<int>(bits.to_ulong());
Można też bardziej generic
template< typename type >
type changeInteger( type number , pair<short int,short int> indices )
{
if( !numeric_limits<type>::is_integer ||
numeric_limits<type>::digits<=indices.first || numeric_limits<type>::digits<=indices.second ||
indices.first<0 || indices.second<0
) throw logic_error("Invalid parameters.");
if( indices.first == indices.second ) return number;
bitset<numeric_limits<unsigned long int>::digits> bits = {static_cast<unsigned long int>( number<0?(-1)*number:number )};
bits[indices.first] = bits[indices.first]^bits[indices.second];
bits[indices.second] = bits[indices.second]^bits[indices.first];
bits[indices.first] = bits[indices.first]^bits[indices.second];
return number<0?static_cast<type>(-1)*static_cast<type>(bits.to_ulong()):static_cast<type>(bits.to_ulong());
}
@TomaszLiMoon: Twoja funkcja jest nie jest dobra, ponieważ niejawnie nie obsługuje typów innych niż całkowite, przez co dostaniemy wynik inny niż spodziewany, gdy użyjemy ją z typami zmiennoprzecinkowymi. Po operacjach na bitset możemy z powrotem otrzymać typ zmiennoprzecinkowy używając to_ullong()
a potem zrobić memcpy bitów.
Powinieneś dodać jakiegoś static asserta pilnującego by przekazywane liczby nie były typu zmiennoprzecinkowego.
Poza tym daje ona niespodziewane rezultaty również dla prostych intów https://wandbox.org/permlink/x169fi9nzwnbP1cZ