Bit manipulation

Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word. Computer programming tasks that require bit manipulation include low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and optimization. For most other tasks, modern programming languages allow the programmer to work directly with abstractions instead of bits that represent those abstractions.

Source code that does bit manipulation makes use of the bitwise operations: AND, OR, XOR, NOT, and possibly other operations analogous to the boolean operators; there are also bit shifts and operations to count ones and zeros, find high and low one or zero, set, reset and test bits, extract and insert fields, mask and zero fields, gather and scatter bits to and from specified bit positions or fields. Integer arithmetic operators can also effect bit-operations in conjunction with the other operators.

Bit manipulation, in some cases, can obviate or reduce the need to loop over a data structure and can give manyfold speed-ups, as bit manipulations are processed in parallel.

Terminology

Bit twiddling, bit fiddling, bit bashing, and bit gymnastics are often used interchangeably with bit manipulation, but sometimes exclusively refer to clever or non-obvious ways or uses of bit manipulation, or tedious or challenging low-level device control data manipulation tasks.

The term bit twiddling dates from early computing hardware, where computer operators would make adjustments by tweaking or twiddling computer controls. As computer programming languages evolved, programmers adopted the term to mean any handling of data that involved bit-level computation.

Bitwise operation

A bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, primitive action directly supported by the central processing unit (CPU), and is used to manipulate values for comparisons and calculations.

On most processors, the majority of bitwise operations are single cycle - substantially faster than division and multiplication and branches. While modern processors usually perform some arithmetic and logical operations just as fast as bitwise operations due to their longer instruction pipelines and other architectural design choices, bitwise operations do commonly use less power because of the reduced use of resources.

Example of bit manipulation

To determine if a number is a power of two, conceptually we may repeatedly do integer divide by two until the number won't divide by 2 evenly; if the only factor left is 1, the original number was a power of 2. Using bit and logical operators, there is a simple expression which will return true (1) or false (0):

bool isPowerOfTwo = (x != 0) && ((x & (x - 1)) == 0);

The second half uses the fact that powers of two have one and only one bit set in their binary representation:

x         == 0...010...0
x-1       == 0...001...1
x & (x-1) == 0...000...0

If the number is neither zero nor a power of two, it will have '1' in more than one place:

x         == 0...1...010...0
x-1       == 0...1...001...1
x & (x-1) == 0...1...000...0

If inline assembly language code is used, then an instruction (popcnt) that counts the number of 1's or 0's in the operand might be available; an operand with exactly one '1' bit is a power of 2. However, such an instruction may have greater latency than the bitwise method above.

Bit manipulation operations

Processors typically provide only a subset of the useful bit operators. Programming languages don't directly support most bit operations, so idioms must be used to code them. The 'C' programming language, for example provides only bit-wise AND(&), OR(|), XOR(^) and NOT(~). Fortran provides AND(.and.), OR (.or.), XOR (.neqv.) and EQV(.eqv.). Algol provides syntactic bitfield extract and insert. When languages provide bit operations that don't directly map to hardware instructions, compilers must synthesize the operation from available operators.

An especially useful bit operation is count leading zeros used to find the high set bit of a machine word, though it may have different names on various architectures.[1] There's no simple programming language idiom, so it must be provided by a compiler intrinsic or system library routine. Without that operator, it is very expensive (see Find first set#CLZ) to do any operations with regard to the high bit of a word, due to the asymmetric carry-propagate of arithmetic operations. Fortunately, most cpu architectures have provided that since the middle 1980s. An accompanying operation count ones, also called POPCOUNT, which counts the number of set bits in a machine word, is also usually provided as a hardware operator. Simpler bit operations like bit set, reset, test and toggle are often provided as hardware operators, but are easily simulated if they aren't - for example (SET R0, 1; LSHFT R0, i; OR x, R0) sets bit i in operand x.

Some of the more useful and complex bit operations that must be coded as idioms in the programming language and synthesized by compilers include:

  • clear from specified bit position up (leave lower part of word)
  • clear from specified bit position down (leave upper part of word)
  • mask from low bit down (clear lower word)
  • mask from high bit up (clear lower word)
  • bitfield extract
  • bitfield insert
  • bitfield scatter/gather operations which distribute contiguous portions of a bitfield over a machine word, or gather disparate bitfields in the word into a contiguous portion of a bitfield (see recent Intel PEXT/PDEP operators). Used by cryptography and video encoding.
  • matrix inversion

Some arithmetic operations can be reduced to simpler operations and bit operations:

  • reduce multiply by constant to sequence of shift-add

Multiply by 9 for example, is copy operand, shift up by 3 (multiply by 8), and add to original operand.

  • reduce division by constant to sequence of shift-subtract

Masking

A mask is data that is used for bitwise operations, particularly in a bit field.

Using a mask, multiple bits in a Byte, nibble, word (etc.) can be set either on, off or inverted from on to off (or vice versa) in a single bitwise operation. More comprehensive applications of masking, when applied conditionally to operations, are termed predication.

See also

References

  1. ^ On most Intel chips, it's BSR (bitscan reverse), though newer SoCs also have LZCNT (count leading zeros)

Further reading

  • Warren, Henry S. (2013). Hacker's Delight (2nd ed.). Addison–Wesley Professional. p. 512. ISBN 978-0321842688.
  • Knuth, Donald E. (2009). The Art of Computer Programming Volume 4, Fascicle 1: Bitwise tricks & techniques; Binary Decision Diagrams (1st ed.). Addison–Wesley Professional. p. 272. ISBN 978-0321580504. (Draft of Fascicle 1a Archived 2019-10-16 at the Wayback Machine available for download)

Read other articles:

This article is about a settlement in the City Municipality of Ljubljana. For the village in Lower Carniola, see Šentpavel na Dolenjskem. For settlement in the Municipality of Domžale, see Šentpavel pri Domžalah. Place in Lower Carniola, SloveniaŠentpavelŠentpavelŠentpavelLocation in SloveniaCoordinates: 46°0′44.99″N 14°37′0.65″E / 46.0124972°N 14.6168472°E / 46.0124972; 14.6168472Country SloveniaTraditional regionLower CarniolaStatistical regionCent...

 

Pagina del libro al-Munqidh min al-dalal di Al-Ghazali, il quale difese strenuamente il sufismo. Il sufismo[1] o taṣawwuf (in arabo تصوّف) è la dimensione mistica[2] dell'Islam[3]; sono detti sufi quanti praticano tale forma di esperienza. Indice 1 Origini 2 Essenza 3 Terminologia 4 Etimologia 5 Storia 5.1 Origini 5.2 Come una disciplina islamica 6 Diffusione e caratteri del sufismo 6.1 L’espressione artistica e sapienziale dei Sufi 6.2 I sette gradi di eleva...

 

Чеченский государственный драматический театр имени Ханпаши Нурадилова Основан 1 мая 1931 Здание театра Местоположение 364031, Чеченская Республика, г.Грозный, ул. Германа Угрюмова, д. 73 Руководство Директор Хава Лолиевна Ахмадова[1] Художественный руководитель Хава Лол...

Untuk the village in Poland, lihat Solna, Poland. Solna kommunMunicipality Lambang kebesaranCountrySwediaDaerahStockholm CountySeatBagian dari wilayah perkotaan StockholmLuasTemplat:Area Swedish municipality • TotalTemplat:Area Swedish municipality km2 (Formatting error: invalid input when rounding sq mi) • Luas daratanTemplat:Area Swedish municipality km2 (Formatting error: invalid input when rounding sq mi) • Luas perairanTem...

 

1909 Cleveland NapsLeagueAmerican LeagueBallparkLeague ParkCityCleveland, OhioOwnersCharles SomersManagersNap Lajoie, Deacon McGuire← 19081910 → The 1909 Cleveland Naps season was a season in American baseball. The team finished sixth in the American League with a record of 71–82, 27½ games behind the Detroit Tigers. Regular season July 19, 1909: Neal Ball of the Naps executed an unassisted triple play. He caught a line drive, touched second base and tagged the r...

 

この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。出典を追加して記事の信頼性向上にご協力ください。(このテンプレートの使い方)出典検索?: ヒュー・フレイザー アニメーター – ニュース · 書籍 · スカラー · CiNii · J-STAGE · NDL · dlib.jp · ジャパンサーチ · TWL(2015年12月) ポータル ディズ

?Папуга-бронзоголов Самець великого папуги-бронзоголова Біологічна класифікація Домен: Ядерні (Eukaryota) Царство: Тварини (Animalia) Тип: Хордові (Chordata) Клас: Птахи (Aves) Ряд: Папугоподібні (Psittaciformes) Родина: Папугові (Psittacidae) Підродина: PsittacellinaeJoseph, Toon, Schirtzinger, Wright & Schodde, 2012 Рід: Папуга-

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (أبريل 2019) روبرت جاكسون بينيت   معلومات شخصية الميلاد 22 يونيو 1984 (39 سنة)  باتون روج، لويزيانا  مواطنة الولايات المتحدة  الحياة العملية المدرسة الأم جامعة تكساس

 

United States anti-drug law This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Comprehensive Drug Abuse Prevention and Control Act of 1970 – news · newspapers · books · scholar · JSTOR (August 2016) (Learn how and when to remove this template message) Comprehensive Drug Abuse Prevention and Control Act of 1970L...

Not to be confused with New Zealand women's national rugby union team or New Zealand women's national rugby league team. For the men's team, see New Zealand national rugby sevens team. Rugby teamNew Zealand Women's SevensUnionNew Zealand RugbyNickname(s)Black Ferns SevensCoach(es)Cory SweeneyCaptain(s)Sarah HiriniMost capsSarah Hirini (253)Top scorerTyla Nathan-Wong (1,292) Team kit Change kit First international New Zealand 54–0  Japan (15 March 1997)World Cup SevensAppearances4 ...

 

Certificate authority which provides free domain-validated certificates Let's EncryptFormationNovember 18, 2014; 9 years ago (2014-11-18)Founder Electronic Frontier Foundation Mozilla Foundation University of Michigan Akamai Technologies Cisco Systems HeadquartersSan Francisco, California, U.S.Coordinates37°48′01″N 122°27′00″W / 37.800322°N 122.449951°W / 37.800322; -122.449951ServicesX.509 certificate authorityParent organizationInternet ...

 

River in the Scottish Borders and northern England For other rivers with this name, see Tweed River (disambiguation). River TweedThe River Tweed at AbbotsfordLocationCountryUnited KingdomPartScotland, EnglandPhysical characteristicsSourceTweed's Well • locationTweedsmuir, Scottish Borders, Scotland • coordinates55°26′42″N 3°29′46″W / 55.445°N 3.496°W / 55.445; -3.496 MouthNorth Sea • locationBerwick-upon-...

1940 film by D. W. Griffith, Hal Roach, Hal Roach, Jr. This article is about the 1940 film. For the 1966 remake, see One Million Years B.C. For events a million years ago, see Pleistocene. One Million B.C.Theatrical release posterDirected byHal RoachHal Roach Jr.Written byMickell NovackGeorge BakerJoseph FrickertProduced byHal RoachD. W. GriffithStarringVictor Mature Carole LandisLon Chaney Jr.Narrated byConrad NagelCinematographyNorbert BrodineEdited byRay SnyderMusic byWerner R. HeymannProd...

 

1971 song by Carole KingBeautifulScandinavian single with You've Got a Friend on the A-sideSong by Carole Kingfrom the album Tapestry ReleasedFebruary 10, 1971GenreSoft rockLength3:08LabelOdeA&MSongwriter(s)Carole KingProducer(s)Lou Adler Beautiful is a song written by Carole King that was first released on her 1971 award-winning album Tapestry. It has also been covered by other artists, such as Barbra Streisand and Richard Marx, and included on several of King's live albums. It was also ...

 

District in Tokyo, JapanToyama 戸山DistrictToyamaCoordinates: 35°42′13.298″N 139°42′51.224″E / 35.70369389°N 139.71422889°E / 35.70369389; 139.71422889CountryJapanCityTokyoWardShinjukuPopulation (December 1, 2017)[1] • Total9,203Time zoneUTC+9 (JST)Postal code169-0052 (3-18.21)[2]162-0052 (Other)[3]Area code03 Toyama (戸山) is a district of Shinjuku, Tokyo, Japan. It is known for Toyama Heights, one of the first ...

2006 action-adventure video game 2006 video gameBullyNTSC cover art for PlayStation 2Developer(s)Rockstar Vancouver[a]Publisher(s)Rockstar GamesProducer(s)Jeronimo BarreraSteve MartinDesigner(s)Mike SkupaSergei KuprejanovProgrammer(s)Mike SlettPeter GrantArtist(s)Steven OldsWriter(s)Dan HouserJacob KrarupComposer(s)Shawn LeeEngineRenderWareGamebryo[b]Platform(s)PlayStation 2WiiXbox 360WindowsAndroidiOSRelease 17 October 2006 PlayStation 2NA: 17 October 2006EU: 25 October 2006A...

 

Not to be confused with Shaitaan (film). 2011 Indian filmShaitanTheatrical release posterDirected byBejoy NambiarScreenplay byMegha RamaswamyBejoy NambiarProduced byAnurag KashyapSunil BohraGuneet MongaStarringRajeev KhandelwalKalki KoechlinPawan MalhotraShiv PandittGulshan DevaiahNeil BhoopalamKirti KulhariRukhsaar RehmanRajit KapoorSheetal MenonRajkummar RaoCinematographyR. MadhiEdited byA. Sreekar PrasadMusic byPrashant PillaiAmar MohileRanjit BarotAnupam RoyProductioncompaniesTipping Poin...

 

Bandar Udara Niijima新島空港新島空港Niijima KūkōFoto udara Bandar Udara Niijima pada tahun 1978IATA: noneICAO: RJANInformasiJenisPublikPengelolaTokyo MetropolitanMelayaniDesa Niijima, JepangLokasiNiijima, JepangKetinggian dpl mdplPetaRJANLokasi di JepangLandasan pacu Arah Panjang Permukaan m kaki 11/29 800 2.625 Aspal beton Bandar Udara Niijima (新島空港code: ja is deprecated , Niijima Kūkō) (ICAO: RJAN)[1] merupakan sebuah lapangan udara publik yang terletak...

Constituency of the National Assembly of France 1st constituency of MancheinlineConstituency of the National Assembly of FranceDeputyPhilippe GosselinLRDepartmentMancheCantonsCanisy - Carentan - Marigny - Montebourg - Percy - Saint-Clair-sur-l'Elle - Saint-Jean-de-Daye - Saint-Lô-Ouest - Saint-Lô-Est - Sainte-Mère-Église - Tessy-sur-Vire - Torigni-sur-Vire - Villedieu-les-PoêlesRegistered voters121,610 Politics of France Political parties Elections Previous Next The 1st constituency of M...

 

Exterior Interior Our Lady of Grace and St Teresa of Avila is a Grade II listed Roman Catholic church at 1 King's Road, Chingford, London, E4 7HP.[1] It was built in 1930 by the architect George W. Martyn with extensions in 1939 and 1956. References ^ Historic England, Our Lady of Grace and St Teresa of Avila Chingford (1271998), National Heritage List for England, retrieved 6 September 2014 External links Media related to Our Lady of Grace and St Teresa of Avila's church, Chingford a...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!