OpenTTD Source: src/core/bitmath_func.hpp File Reference

OpenTTD Source 15.0-RC2

Data Structures | Functions
bitmath_func.hpp File Reference

Functions related to bit mathematics. More...

Go to the source code of this file.

## Data Structures
struct | SetBitIterator< Tbitpos, Tbitset >
| Iterable ensemble of each set bit in a value. More...
struct | SetBitIterator< Tbitpos, Tbitset >::Iterator

## Functions
template<typename T >
static constexpr uint | GB (const T x, const uint8_t s, const uint8_t n)
| Fetch n bits from x, started at bit s.
template<typename T , typename U >
constexpr T | SB (T &x, const uint8_t s, const uint8_t n, const U d)
| Set n bits in x starting at bit s to d.
template<typename T , typename U >
constexpr T | AB (T &x, const uint8_t s, const uint8_t n, const U i)
| Add i to n bits of x starting at bit s.
template<typename T >
constexpr bool | HasBit (const T x, const uint8_t y)
| Checks if a bit in a value is set.
template<typename T >
constexpr T | SetBit (T &x, const uint8_t y)
| Set a bit in a variable.
template<typename T >
constexpr T | ClrBit (T &x, const uint8_t y)
| Clears a bit in a variable.
template<typename T >
constexpr T | ToggleBit (T &x, const uint8_t y)
| Toggles a bit in a variable.
template<typename T >
constexpr T | AssignBit (T &x, const uint8_t y, bool value)
| Assigns a bit in a variable.
template<typename T >
constexpr uint8_t | FindFirstBit (T x)
| Search the first set bit in a value.
template<typename T >
constexpr uint8_t | FindLastBit (T x)
| Search the last set bit in a value.
template<typename T >
constexpr T | KillFirstBit (T value)
| Clear the first bit in an integer.
template<typename T >
constexpr uint | CountBits (T value)
| Counts the number of set bits in a variable.
template<typename T >
constexpr bool | HasExactlyOneBit (T value)
| Test whether value has exactly 1 bit set.
template<typename T >
constexpr bool | HasAtMostOneBit (T value)
| Test whether value has at most 1 bit set.
template<typename T >
constexpr enable_if_t< is_integral_v< T >, T > | std::byteswap (T x) noexcept
| Custom implementation of std::byteswap; remove once we build with C++23.

## Detailed Description

Functions related to bit mathematics.

Definition in file bitmath_func.hpp.

## Function Documentation

## ◆ AB()

template<typename T , typename U >

constexpr T AB | ( | T & | x,
|  | const uint8_t | s,
|  | const uint8_t | n,
|  | const U | i
| ) |  |
| constexpr

Add i to n bits of x starting at bit s.

This adds the value of i on n bits of x starting at bit s. The parameters x, s, i are similar to GB. Besides, \ a x must be a variable as the result are saved there. An overflow does not affect the following bits of the given bit window and is simply ignored.

Note
  Parameter x must be a variable as the result is saved there.

Parameters

  x | The variable to add some bits at some position
  s | The start position of the addition
  n | The size/window for the addition

Precondition
  n < sizeof(T) * 8
  s + n <= sizeof(T) * 8

Parameters

  i | The value to add at the given start position in the given window.

Returns
  The new value of x

Definition at line 83 of file bitmath_func.hpp.

Referenced by IncHouseConstructionTick(), and IncreaseRoadWorksCounter().

## ◆ AssignBit()

template<typename T >

constexpr T AssignBit | ( | T & | x,
|  | const uint8_t | y,
|  | bool | value
| ) |  |
| constexpr

Assigns a bit in a variable.

This function assigns a single bit in a variable. The variable is changed and the value is also returned. Parameter y defines the bit to assign and starts at the LSB with 0.

Parameters

  x | The variable to assign the bit
  y | The bit position to assign
  value | The new bit value

Precondition
  y < sizeof(T) * 8

Returns
  The new value of the old value with the bit assigned

Definition at line 176 of file bitmath_func.hpp.

Referenced by AfterLoadGame(), AircraftVehicleChangeInfo(), BuildGuiGroupList(), VehicleOrderSaver::Restore(), SetCrossingBarred(), SetCrossingReservation(), SetDepotReservation(), SetDockingTile(), SetNonFloodingWaterTile(), SetRailStationReservation(), SetStationTileBlocked(), SetStationTileHavePylons(), SetStationTileHaveWires(), SetTrackReservation(), Order::SetTravelTimetabled(), SetTunnelBridgeReservation(), and Order::SetWaitTimetabled().

## ◆ byteswap()

template<typename T >

constexpr enable_if_t< is_integral_v< T >, T > std::byteswap | ( | T | x | ) |
| constexprprivatenoexcept

Custom implementation of std::byteswap; remove once we build with C++23.

Perform an endianness bitswap on x.

Parameters

  x | the variable to bitswap

Returns
  the bitswapped value.

Definition at line 330 of file bitmath_func.hpp.

References std::byteswap().

Referenced by std::byteswap().

## ◆ ClrBit()

template<typename T >

constexpr T ClrBit | ( | T & | x,
|  | const uint8_t | y
| ) |  |
| constexpr

Clears a bit in a variable.

This function clears a bit in a variable. The variable is changed and the value is also returned. Parameter y defines the bit to clear and starts at the LSB with 0.

Parameters

  x | The variable to clear the bit
  y | The bit position to clear

Precondition
  y < sizeof(T) * 8

Returns
  The new value of the old value with the bit cleared

Definition at line 139 of file bitmath_func.hpp.

Referenced by AfterLoadGame(), AircraftController(), AircraftHandleDestTooFar(), Vehicle::BeginLoading(), CalculateRefitMasks(), CargoReserveInfo(), GroundVehicle< T, Type >::ClearArticulatedPart(), GroundVehicle< T, Type >::ClearEngine(), GroundVehicle< T, Type >::ClearFreeWagon(), GroundVehicle< T, Type >::ClearFrontEngine(), GroundVehicle< T, Type >::ClearMultiheaded(), ClearSingleBridgeMiddle(), ClearSnow(), GroundVehicle< T, Type >::ClearWagon(), ConvertOldMultiheadToNew(), GroundVehicle< T, Type >::Crash(), DEFINE_POOL_METHOD(), Vehicle::DeleteUnreachedImplicitOrders(), FeatureTownName(), LoadUnloadVehicle(), MapSpriteMappingRecolour(), PickerWindow::OnClick(), SelectCompanyLiveryWindow::OnInvalidateData(), OpenBankFile(), PrepareToEnterBridge(), ReadSpriteLayout(), ReadSpriteLayoutSprite(), FreeUnitIDGenerator::ReleaseID(), RemoveFirstTrack(), RemoveFirstTrackdir(), SwapTrainFlags(), ToggleInvisibilityWithTransparency(), SelectCompanyManagerFaceWindow::UpdateData(), and GroundVehicle< T, Type >::UpdateZPositionAndInclination().

## ◆ CountBits()

template<typename T >

constexpr uint CountBits | ( | T | value | ) |
| constexpr

Counts the number of set bits in a variable.

Parameters

  value | the value to count the number of bits in.

Returns
  the number of bits.

Definition at line 238 of file bitmath_func.hpp.

Referenced by CheckFlatLandRoadStop(), CmdBuildRoad(), CmdBuildRoadStop(), CmdBuildRoadWaypoint(), CmdBuildSingleRail(), CmdBuildSingleSignal(), CmdConvertRail(), CmdConvertRoad(), CmdGoalQuestion(), CmdRemoveSingleRail(), CmdRemoveSingleSignal(), BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Count(), DrawRoadTypeCatenary(), RailTypeScopeResolver::GetRandomBits(), RoadTypeScopeResolver::GetRandomBits(), CYapfFollowShipT< Types >::GetRandomTrackdir(), CompanyStationsWindow::GetWidgetString(), RemoveGenericRoadStop(), RemoveRoad(), ShowRefitOptionsList(), and TownGenerateCargoBinomial().

## ◆ FindFirstBit()

template<typename T >

constexpr uint8_t FindFirstBit | ( | T | x | ) |
| constexpr

Search the first set bit in a value.

When no bit is set, it returns 0.

Parameters

  x | The value to search.

Returns
  The position of the first bit set.

Definition at line 189 of file bitmath_func.hpp.

Referenced by CYapfBaseT< Types >::AddMultipleNodes(), Map::Allocate(), CalculateRefitMasks(), CheckFlatLandRoadStop(), DEFINE_POOL_METHOD(), ExploreSegment(), FindFirstTrack(), FindFirstTrackdir(), CompanyStationsWindow::GetWidgetString(), FreeUnitIDGenerator::NextID(), CYapfCostRoadT< Types >::PfCalcCost(), CYapfCostRailT< Types >::PfCalcCost(), RemoveFirstTrack(), RemoveFirstTrackdir(), RoadFindPathToDest(), CYapfOriginTileT< Types >::SetOrigin(), TrackBitsToTrack(), TrainController(), and YapfRoadVehicleChooseTrack().

## ◆ FindLastBit()

template<typename T >

constexpr uint8_t FindLastBit | ( | T | x | ) |
| constexpr

Search the last set bit in a value.

When no bit is set, it returns 0.

Parameters

  x | The value to search.

Returns
  The position of the last bit set.

Definition at line 208 of file bitmath_func.hpp.

## ◆ GB()

template<typename T >

static constexpr uint GB | ( | const T | x,
|  | const uint8_t | s,
|  | const uint8_t | n
| ) |  |
| inlinestaticconstexpr

Fetch n bits from x, started at bit s.

This function can be used to fetch n bits from the value x. The s value set the start position to read. The start position is count from the LSB and starts at `0`. The result starts at a LSB, as this isn't just an and-bitmask but also some bit-shifting operations. GB(0xFF, 2, 1) will so return 0x01 (0000 0001) instead of 0x04 (0000 0100).

Parameters

  x | The value to read some bits.
  s | The start position to read some bits.
  n | The number of bits to read.

Precondition
  n < sizeof(T) * 8
  s + n <= sizeof(T) * 8

Returns
  The selected bits, aligned to a LSB.

Definition at line 32 of file bitmath_func.hpp.

Referenced by AddAcceptedCargoOfHouse(), AfterLoadGame(), AirportChangeInfo(), AmbientSoundEffectCallback(), AnimationBase< Tbase, Tspec, Tobj, Textra, GetCallback, Tframehelper >::AnimateTile(), BmpRead1(), BmpRead24(), BmpRead4(), BmpRead4Rle(), BmpRead8(), BuildObject(), BuildTownHouse(), AnimationBase< Tbase, Tspec, Tobj, Textra, GetCallback, Tframehelper >::ChangeAnimationFrame(), ChangeIndustryProduction(), ChangeTrainDirRandomly(), CheckPartialPixelZ(), CmdBuildAirport(), CmdBuildIndustry(), CmdBuildObject(), CmdBuildObjectArea(), CmdBuildRailStation(), CmdBuildRoadStop(), CmdClearArea(), CmdLandscapeClear(), CmdLevelLand(), CmdPlantTree(), CmdStartStopVehicle(), CmdTerraformLand(), Convert8bitBooleanCallback(), ConvertFromOldCompanyManagerFace(), Blitter_32bppAnim::CopyFromBuffer(), CopyFromOldName(), CreateNewIndustry(), DecodeMonitorCargoType(), DecodeMonitorCompany(), DecodeMonitorIndustry(), DecodeMonitorTown(), DecodeUtf8(), Disaster_CoalMine_Init(), DisasterTick_Aircraft(), DisasterTick_Big_Ufo_Destroyer(), DisasterTick_Submarine(), DisasterTick_Zeppeliner(), DoCreateNewIndustry(), Blitter_32bppOptimized::Draw(), Blitter_40bppAnim::Draw(), DrawCommonTileSeq(), DrawCommonTileSeqInGUI(), DrawNewHouseTileInGUI(), DrawNewObjectTileInGUI(), DrawRoadStopTile(), DrawSprite(), DrawSpriteToRgbaBuffer(), DrawSpriteViewport(), DrawTileLayout(), EncodeUtf8(), FeatureTownName(), FormatLabel(), FormatString(), AI::GameLoop(), GenerateCompanyColour(), GenerateLandscape(), GenerateTrees(), GenRandomRoadBits(), GetAiPurchaseCallbackResult(), GetAnimatedTileState(), FaceVar::GetBits(), GetBridgeAxis(), GetBridgeType(), GetCargoSuffix(), GetCleanHouseType(), GetCleanIndustryGfx(), GetClearCounter(), GetClearDensity(), GetClearGround(), StoryPageButtonData::GetColour(), Order::GetConditionComparator(), Order::GetConditionValue(), Order::GetConditionVariable(), GetCountAndDistanceOfClosestInstance(), GetCrossingRoadAxis(), StoryPageButtonData::GetCursor(), GetCustomRoadStopSpecIndex(), Order::GetDepotActionType(), Order::GetDepotOrderType(), GetDisallowedRoadDirections(), GetDistanceFromNearbyHouse(), GetFeatureIndex(), GetFeatureNum(), GetFence(), GetFieldType(), GetGlobalVariable(), GetHouseBuildingStage(), GetHouseConstructionTick(), BuildHouseWindow::GetHouseInformation(), GetHouseProcessingTime(), GetHouseRandomTriggers(), GetIndustryConstructionCounter(), GetIndustryConstructionStage(), GetIndustryRandomTriggers(), GetLiftDestination(), GetLiftPosition(), GetLoadAmount(), Order::GetLoadType(), GetLockDirection(), GetLockPart(), GetNearbyTile(), Waypoint::GetNewGRFVariable(), GetNextArticulatedPart(), Order::GetNonStopType(), GetPresentSignals(), GetProducedCargoOfHouse(), GetRailDepotDirection(), GetRailReservationTrackBits(), GetRailTileType(), GetRailType(), RailTypeScopeResolver::GetRandomBits(), RoadTypeScopeResolver::GetRandomBits(), GetRefitCostFactor(), GetRoadBits(), GetRoadDepotDirection(), GetRoadOwner(), GetRoadside(), GetRoadTileType(), GetRoadWaypointRoadside(), VehicleResolverObject::GetScope(), GetShipDepotAxis(), GetShipDepotPart(), GetSignalStates(), GetStationTileRandomBits(), GetStationType(), Order::GetStopLocation(), GetSurname(), GetTileHash1D(), GetTileLocationGroup(), GetTileOwner(), GetTileType(), GetTrackBits(), GetTreeCount(), GetTreeDensity(), GetTreeGround(), GetTreeGrowth(), GetTropicZone(), GetTunnelBridgeDirection(), GetTunnelBridgeTransportType(), Order::GetType(), Order::GetUnloadType(), GRFConfig::GetValue(), GetVarFileType(), VehicleScopeResolver::GetVariable(), HouseScopeResolver::GetVariable(), IndustriesScopeResolver::GetVariable(), StationScopeResolver::GetVariable(), TownScopeResolver::GetVariable(), GetVarMemType(), StoryPageButtonData::GetVehicleType(), GetWaterClass(), GetWaterTileType(), BuildObjectWindow::GetWidgetString(), GfxFillPolygon(), GfxFillRect(), GlobalVarChangeInfo(), HandleAutoSignalPlacement(), HandleCrashedAircraft(), HandleCrashedTrain(), HeightMapNormalize(), IncHouseConstructionTick(), IncreaseRoadWorksCounter(), IndustriesChangeInfo(), IndustrytilesChangeInfo(), IsBridgeAbove(), IsCustomRoadStopSpecIndex(), FaceVar::IsValid(), IsWaypointClass(), IsWaypointClass(), MAPEChunkHandler::Load(), ORDRChunkHandler::Load(), VEHSChunkHandler::Load(), LoadChunk(), MapNewGRFIndustryType(), Order::MapOldOrder(), MaybeCrashAirplane(), MirrorRoadBits(), MoveWaypointsToBaseStations(), ObjectChangeInfo(), OrdersWindow::OnInvalidateData(), TimetableWindow::OnInvalidateData(), VehicleListWindow::OnInvalidateData(), OpenBankFile(), Blitter_32bppAnim::PaletteAnimate(), ParamSet(), ParseCompanyManagerFaceCode(), PlaceTree(), PlaceTreeAtSameHeight(), PlaceTreeGroups(), PlantRandomTree(), Packet::PrepareToSend(), ReadSpriteLayoutSprite(), ReallyAdjustBrightness(), OpenGLBackend::RenderOglSprite(), ResetRestoreAllTransparency(), DeterministicSpriteGroup::Resolve(), RotateRoadBits(), SeedChance(), Packet::Send_uint16(), Packet::Send_uint32(), Packet::Send_uint64(), SetIndustryGfx(), SetWaterClassDependingOnSurroundings(), Vehicle::ShowVisualEffect(), SpawnAdvancedVisualEffect(), StartupOneEngine(), TileHash2Bit(), TileLoop_Town(), TownGenerateCargoOriginal(), TownHouseChangeInfo(), TrainCheckIfLineEnds(), TriggerHouseAnimation_TileLoop(), TryBuildLightHouse(), UnpackVersion4Order(), UpdateCursorSize(), UpdateStationRating(), UpdateValidHistory(), Vehicle::UpdateVisualEffect(), StoryPageButtonData::ValidateColour(), StoryPageButtonData::ValidateCursor(), StoryPageButtonData::ValidateVehicleType(), and EndianBufferWriter< Tcont, Titer >::Write().

## ◆ HasAtMostOneBit()

template<typename T >

constexpr bool HasAtMostOneBit | ( | T | value | ) |
| constexpr

Test whether value has at most 1 bit set.

Parameters

  value | the value to test.

Returns
  does value have at most 1 bit set?

Definition at line 266 of file bitmath_func.hpp.

Referenced by DrawRoadBits(), ExploreSegment(), GetNewCargoTypeForReplace(), MaskWireBits(), Vehicle::NeedsServicing(), and ShowRefitOptionsList().

## ◆ HasBit()

template<typename T >

constexpr bool HasBit | ( | const T | x,
|  | const uint8_t | y
| ) |  |
| inlineconstexpr

Checks if a bit in a value is set.

This function checks if a bit inside a value is set or not. The y value specific the position of the bit, started at the LSB and count from `0`.

Parameters

  x | The value to check
  y | The position of the bit to check, started from the LSB

Precondition
  y < sizeof(T) * 8

Returns
  True if the bit is set, false else.

Definition at line 103 of file bitmath_func.hpp.

Referenced by AddAcceptedCargoOfHouse(), AfterLoadGame(), AircraftHandleDestTooFar(), Vehicle::BeginLoading(), BaseVehicleListWindow::BuildCargoDropDownList(), GameOptionsWindow::BuildDropDownList(), BuildObject(), PickerWindow::BuildPickerClassList(), PickerWindow::BuildPickerTypeList(), RefitWindow::BuildRefitList(), CompanyStationsWindow::BuildStationsList(), CalculateRefitMasks(), CanStationTileHavePylons(), CanStationTileHaveWires(), CargoAndEngineFilter(), CargoesField::CargoClickedAt(), ChangeIndustryProduction(), CheckClickOnViewportSign(), CheckFlatLandRailStation(), CheckIfIndustryTilesAreFree(), CheckRoadBlockedForOvertaking(), BuildRailStationWindow::CheckSelectedSize(), CheckTrainsOnTrack(), ChooseShipTrack(), CmdBuildObject(), CmdBuildRailStation(), CmdBuildRailWaypoint(), CmdBuildRoad(), CmdBuildRoadWaypoint(), CmdBuildSingleRail(), CmdBuildSingleSignal(), CmdSignalTrackHelper(), CmdStartStopVehicle(), CompaniesGenStatistics(), CargoesField::ConnectCargo(), CargoesRow::ConnectIndustryAccepted(), CargoesRow::ConnectIndustryProduced(), Train::ConsistChanged(), ConvertFromOldCompanyManagerFace(), ConvertOldMultiheadToNew(), CreateGroupFromGroupID(), DecodeUtf8(), Vehicle::DeleteUnreachedImplicitOrders(), DeliverGoods(), DisasterTick_Aircraft(), DisasterTick_Helicopter_Rotors(), DisasterTick_Submarine(), DisasterTick_Ufo(), DisasterTick_Zeppeliner(), BaseSettingEntry::Draw(), CargoesField::Draw(), DrawBridgeMiddle(), DrawCanalWater(), DrawCommonTileSeq(), DrawCommonTileSeqInGUI(), DrawEngineList(), BaseGraphWindow::DrawGraph(), VehicleGroupWindow::DrawGroupInfo(), DrawNewHouseTileInGUI(), DrawRailCatenaryOnBridge(), DrawRailCatenaryRailway(), DrawRoadBits(), DrawSprite(), DrawSpriteViewport(), DrawStationTile(), DrawWaterLock(), SelectCompanyLiveryWindow::DrawWidget(), BaseGraphWindow::DrawWidget(), BaseCargoGraphWindow::DrawWidget(), TransparenciesWindow::DrawWidget(), FeatureTownName(), FillNewGRFVehicleCache(), WaypointPickerCallbacks::FillUsedItems(), RoadWaypointPickerCallbacks::FillUsedItems(), SignList::FilterSignList(), FindDeletedWaypointCloseTo(), FindJoiningWaypoint(), FixOwnerOfRailTrack(), FormatString(), GetActiveFaceVars(), GetBestFittingSubType(), HousePickerCallbacks::GetClassName(), GetHistory(), GetIncompatibleRefitOrderIdForAutoreplace(), GetNewCargoTypeForReplace(), GetNextArticulatedPart(), Airport::GetNumHangars(), GetPreviewCompany(), GetRailReservationTrackBits(), GetRailStationAxis(), GetRefitCostFactor(), GetSingleSignalState(), GroundVehicle< T, Type >::GetSlopeResistance(), BaseGraphWindow::GetValuesInterval(), HouseScopeResolver::GetVariable(), IndustriesScopeResolver::GetVariable(), StationScopeResolver::GetVariable(), SelectCompanyLiveryWindow::GetWidgetString(), BuildObjectWindow::GetWidgetString(), GroundSpritePaletteTransform(), LinkRefresher::HandleRefit(), HasCPUIDFlag(), HasCrossingReservation(), HasDepotReservation(), HasStationReservation(), HasTrack(), HasTrack(), HasTrackdir(), HasTunnelBridgeReservation(), HasTunnelBridgeSnowOrDesert(), HeightMapCurves(), Vehicle::IsArticulatedPart(), IsBridge(), IsCrossingBarred(), IsDockingTile(), GroundVehicle< T, Type >::IsEngine(), GroundVehicle< T, Type >::IsFreeWagon(), Vehicle::IsFrontEngine(), IsHouseCompleted(), IsHouseProtected(), IsIndustryCompleted(), IsInvisibilitySet(), GroundVehicle< T, Type >::IsMultiheaded(), IsNonFloodingWaterTile(), IsOnSnowOrDesert(), CYapfCostShipT< Types >::IsPreferredShipDirection(), IsRoadWaypointOnSnowOrDesert(), IsSignalPresent(), IsSnowTile(), IsStationTileBlocked(), IsTransparencySet(), Order::IsTravelTimetabled(), IsTunnel(), IsUphillTrackdir(), IsValidHistory(), GroundVehicle< T, Type >::IsWagon(), Order::IsWaitTimetabled(), RoadStop::Leave(), LiftHasDestination(), MakeDefaultName(), MapNewGRFIndustryType(), MapSpriteMappingRecolour(), MonitorMonitorsIndustry(), MoveWaypointsToBaseStations(), Vehicle::NeedsServicing(), SelectCompanyLiveryWindow::OnClick(), BaseGraphWindow::OnClick(), BaseCargoGraphWindow::OnClick(), OskWindow::OnClick(), PickerWindow::OnClick(), BuildRailStationWindow::OnClick(), SelectCompanyLiveryWindow::OnDropdownSelect(), SelectCompanyLiveryWindow::OnInvalidateData(), PickerWindow::OnInvalidateData(), TimetableWindow::OnInvalidateData(), VehicleListWindow::OnInvalidateData(), BaseGraphWindow::OnMouseOver(), BuildRailStationWindow::OnPaint(), OpenBankFile(), SignList::OwnerVisibilityFilter(), ParamSet(), PerformStationTileSlopeCheck(), PrepareToEnterBridge(), SpriteLayoutProcessor::ProcessRegisters(), RailVehicleChangeInfo(), ReadSpriteLayout(), ReadSpriteLayoutSprite(), RefitVehicle(), RemoveRoadStop(), RoadFindPathToDest(), RoadVehicleChangeInfo(), RotateHistory(), RunEconomyVehicleDayProc(), BuildVehicleWindow::SetCargoFilterArray(), LinkGraphLegendWindow::SetOverlay(), ShipVehicleChangeInfo(), ShowDropDownMenu(), Vehicle::ShowVisualEffect(), SlReadSimpleGamma(), SpawnAdvancedVisualEffect(), SpriteLayoutPaletteTransform(), SpriteLayoutProcessor::SpriteLayoutProcessor(), StationChangeInfo(), SubtractMoneyFromAnyCompany(), SwapTrainFlags(), SwitchNewGRFBlitter(), ToolbarOptionsClick(), TownHouseChangeInfo(), TrackOverlapsTracks(), TriggerRoadStopRandomisation(), TriggerStationRandomisation(), OskWindow::UpdateOskState(), UpdateStationRating(), UpdateValidHistory(), Vehicle::UpdateVisualEffect(), GroundVehicle< T, Type >::UpdateZPosition(), VehicleExitDir(), VerifyAutoreplaceRefitForOrders(), VisitAdjacentWaterRegionPatchNeighbours(), and WaypointWindow::WaypointWindow().

## ◆ HasExactlyOneBit()

template<typename T >

constexpr bool HasExactlyOneBit | ( | T | value | ) |
| constexpr

Test whether value has exactly 1 bit set.

Parameters

  value | the value to test.

Returns
  does value have exactly 1 bit set?

Definition at line 254 of file bitmath_func.hpp.

Referenced by CheckFlatLandRoadStop(), CheckRoadSlope(), CmdBuildRoad(), and CmdBuildSingleRail().

## ◆ KillFirstBit()

template<typename T >

constexpr T KillFirstBit | ( | T | value | ) |
| constexpr

Clear the first bit in an integer.

This function returns a value where the first bit (from LSB) is cleared. So, 110100 returns 110000, 000001 returns 000000, etc.

Parameters

  value | The value to clear the first bit

Returns
  The new value with the first bit cleared

Definition at line 226 of file bitmath_func.hpp.

Referenced by CYapfBaseT< Types >::AddMultipleNodes(), CheckAllowRemoveRoad(), CheckNextTrainTile(), CmdBuildSingleSignal(), ExtendTrainReservation(), IsSafeWaitingPosition(), CYapfCostRoadT< Types >::PfCalcCost(), CYapfCostRailT< Types >::PfCalcCost(), RoadFindPathToDest(), CYapfOriginTileT< Types >::SetOrigin(), TrackBitsToTrack(), and TracksOverlap().

## ◆ SB()

template<typename T , typename U >

constexpr T SB | ( | T & | x,
|  | const uint8_t | s,
|  | const uint8_t | n,
|  | const U | d
| ) |  |
| constexpr

Set n bits in x starting at bit s to d.

This function sets n bits from x which started as bit s to the value of d. The parameters x, s and n works the same as the parameters of GB. The result is saved in x again. Unused bits in the window provided by n are set to 0 if the value of d isn't "big" enough. This is not a bug, its a feature.

Note
  Parameter x must be a variable as the result is saved there.
  To avoid unexpected results the value of d should not use more space as the provided space of n bits (log2)

Parameters

  x | The variable to change some bits
  s | The start position for the new bits
  n | The size/window for the new bits
  d | The actually new bits to save in the defined position.

Precondition
  n < sizeof(T) * 8
  s + n <= sizeof(T) * 8

Returns
  The new value of x

Definition at line 58 of file bitmath_func.hpp.

Referenced by AfterLoadGame(), AircraftVehicleChangeInfo(), EncodeCargoIndustryMonitor(), EncodeCargoTownMonitor(), RoadStop::Enter(), FixOwnerOfRailTrack(), GetGlobalVariable(), GetPlatformInfo(), HaltLift(), IndustriesChangeInfo(), IndustryProductionCallback(), MakeBridgeRamp(), MakeField(), MakeHouseTile(), MakeIndustry(), MakeLockTile(), MakeObject(), MakeRailDepot(), MakeRailTunnel(), MakeRoadCrossing(), MakeRoadDepot(), MakeRoadNormal(), MakeRoadTunnel(), MakeShipDepot(), MakeShore(), MakeStation(), MakeTree(), MakeWater(), MoveBuoysToWaypoints(), RailVehicleChangeInfo(), ReadSpriteLayoutSprite(), ResetIndustryConstructionStage(), RoadVehicleChangeInfo(), SetAnimatedTileState(), FaceVar::SetBits(), SetClearCounter(), SetClearDensity(), StoryPageButtonData::SetColour(), Order::SetConditionComparator(), Order::SetConditionValue(), Order::SetConditionVariable(), StoryPageButtonData::SetCursor(), SetCustomRoadStopSpecIndex(), Order::SetDepotActionType(), Order::SetDepotOrderType(), SetDisallowedRoadDirections(), SetFence(), SetFieldType(), SetHasSignals(), SetHouseCompleted(), SetHouseProcessingTime(), SetHouseProtected(), SetHouseRandomTriggers(), SetHouseType(), SetIndustryConstructionCounter(), SetIndustryConstructionStage(), SetIndustryGfx(), SetIndustryRandomTriggers(), SetLiftDestination(), SetLiftPosition(), Order::SetLoadType(), Order::SetNonStopType(), SetPresentSignals(), SetRailDepotExitDirection(), SetRailType(), SetRoadBits(), SetRoadDepotExitDirection(), SetRoadOwner(), SetRoadside(), SetRoadTypeRoad(), SetRoadTypeTram(), SetRoadWaypointRoadside(), SetSignalStates(), SetStationTileRandomBits(), Order::SetStopLocation(), GRFConfig::SetSuitablePalette(), SetTileOwner(), SetTileType(), SetTrackBits(), SetTrackReservation(), SetTreeGroundDensity(), SetTreeGrowth(), SetTropicZone(), SetTunnelBridgeSnowOrDesert(), Order::SetUnloadType(), GRFConfig::SetValue(), StoryPageButtonData::SetVehicleType(), SetWaterClass(), SetWaterTileType(), ShipVehicleChangeInfo(), TerminateRoadWorks(), TownHouseChangeInfo(), TriggerObjectAnimation(), UpdateValidHistory(), Vehicle::UpdateVisualEffect(), and VerifyOldNameChecksum().

## ◆ SetBit()

template<typename T >

constexpr T SetBit | ( | T & | x,
|  | const uint8_t | y
| ) |  |
| constexpr

Set a bit in a variable.

This function sets a bit in a variable. The variable is changed and the value is also returned. Parameter y defines the bit and starts at the LSB with 0.

Parameters

  x | The variable to set a bit
  y | The bit position to set

Precondition
  y < sizeof(T) * 8

Returns
  The new value of the old value with the bit set

Definition at line 121 of file bitmath_func.hpp.

Referenced by AddAcceptedCargoSetMask(), AddChildSpriteScreen(), AddSortableSpriteToDraw(), AfterLoadGame(), AircraftController(), AircraftHandleDestTooFar(), AircraftVehicleChangeInfo(), CalculateRefitMasks(), CargoReserveInfo(), CheckConsistencyOfArticulatedVehicle(), CheckIfTrainNeedsService(), CmdBuildRoadWaypoint(), CmdSignalTrackHelper(), CargoesField::ConnectCargo(), ConvertOldMultiheadToNew(), GoodsEntry::ConvertState(), DEFINE_POOL_METHOD(), DisplayVehicleSortDropDown(), SettingsPage::Draw(), DrawCommonTileSeq(), DrawCustomStationFoundations(), DrawStationCoverageAreaText(), BaseVehicleListWindow::DrawVehicleListItems(), EncodeCargoIndustryMonitor(), RoadStop::Enter(), FinaliseEngineArray(), WaterRegion::ForceUpdate(), GetAcceptanceMask(), GetAvailableVehicleCargoTypes(), GetCargoTypesOfArticulatedParts(), GetCargoTypesOfArticulatedVehicle(), GetCountAndDistanceOfClosestInstance(), GetEmptyMask(), GetMaskOfAllowedCurrencies(), Airport::GetNumHangars(), GetProducedCargoOfHouse(), HouseScopeResolver::GetVariable(), RoadStopScopeResolver::GetVariable(), InitializeSortedCargoSpecs(), InsertOrder(), IsEngineRefittable(), LoadUnloadVehicle(), LookupManyOfMany(), MakeDefaultName(), MakeSnow(), Order::MapOldOrder(), MapSpriteMappingRecolour(), GenerateLandscapeWindow::OnClick(), PickerWindow::OnClick(), RailVehicleChangeInfo(), ReadSpriteLayoutSprite(), RoadVehicleChangeInfo(), Vehicle::SendToDepot(), GroundVehicle< T, Type >::SetArticulatedPart(), SetBridgeMiddle(), HousePickerCallbacks::SetClimateMask(), GroundVehicle< T, Type >::SetEngine(), GroundVehicle< T, Type >::SetFreeWagon(), GroundVehicle< T, Type >::SetFrontEngine(), SetIndustryCompleted(), SetLiftDestination(), GroundVehicle< T, Type >::SetMultiheaded(), SmallMapWindow::SetOverlayCargoMask(), GroundVehicle< T, Type >::SetWagon(), ShipVehicleChangeInfo(), SpriteLayoutProcessor::SpriteLayoutProcessor(), SwapTrainFlags(), ToggleInvisibilityWithTransparency(), TownHouseChangeInfo(), TranslateRefitMask(), TriggerWatchedCargoCallbacks(), UpdateOrderDest(), LinkGraphLegendWindow::UpdateOverlayCargoes(), Vehicle::UpdateVisualEffect(), GroundVehicle< T, Type >::UpdateZPositionAndInclination(), and FreeUnitIDGenerator::UseID().

## ◆ ToggleBit()

template<typename T >

constexpr T ToggleBit | ( | T & | x,
|  | const uint8_t | y
| ) |  |
| constexpr

Toggles a bit in a variable.

This function toggles a bit in a variable. The variable is changed and the value is also returned. Parameter y defines the bit to toggle and starts at the LSB with 0.

Parameters

  x | The variable to toggle the bit
  y | The bit position to toggle

Precondition
  y < sizeof(T) * 8

Returns
  The new value of the old value with the bit toggled

Definition at line 157 of file bitmath_func.hpp.

Referenced by CmdBuildObject(), CmdRailTrackHelper(), CmdSignalTrackHelper(), MenuClickSettings(), SelectCompanyLiveryWindow::OnClick(), BaseGraphWindow::OnClick(), BaseCargoGraphWindow::OnClick(), OskWindow::OnClick(), PickerWindow::OnClick(), CompanyStationsWindow::OnDropdownSelect(), PerformStationTileSlopeCheck(), ToggleInvisibility(), ToggleRoadWaypointOnSnowOrDesert(), ToggleSnowOrDesert(), ToggleTransparency(), ToggleTransparencyLock(), and Vehicle::UpdateVisualEffect().