Circular shift

Matrices of 8-element circular shifts to the left and right

In combinatorial mathematics, a circular shift is the operation of rearranging the entries in a tuple, either by moving the final entry to the first position, while shifting all other entries to the next position, or by performing the inverse operation. A circular shift is a special kind of cyclic permutation, which in turn is a special kind of permutation. Formally, a circular shift is a permutation σ of the n entries in the tuple such that either

modulo n, for all entries i = 1, ..., n

or

modulo n, for all entries i = 1, ..., n.

The result of repeatedly applying circular shifts to a given tuple are also called the circular shifts of the tuple.

For example, repeatedly applying circular shifts to the four-tuple (a, b, c, d) successively gives

  • (d, a, b, c),
  • (c, d, a, b),
  • (b, c, d, a),
  • (a, b, c, d) (the original four-tuple),

and then the sequence repeats; this four-tuple therefore has four distinct circular shifts. However, not all n-tuples have n distinct circular shifts. For instance, the 4-tuple (a, b, a, b) only has 2 distinct circular shifts. The number of distinct circular shifts of an n-tuple is , where k is a divisor of n, indicating the maximal number of repeats over all subpatterns.

In computer programming, a bitwise rotation, also known as a circular shift, is a bitwise operation that shifts all bits of its operand. Unlike an arithmetic shift, a circular shift does not preserve a number's sign bit or distinguish a floating-point number's exponent from its significand. Unlike a logical shift, the vacant bit positions are not filled in with zeros but are filled in with the bits that are shifted out of the sequence.

Implementing circular shifts

Circular shifts are used often in cryptography in order to permute bit sequences. Unfortunately, many programming languages, including C, do not have operators or standard functions for circular shifting, even though virtually all processors have bitwise operation instructions for it (e.g. Intel x86 has ROL and ROR). However, some compilers may provide access to the processor instructions by means of intrinsic functions. In addition, some constructs in standard ANSI C code may be optimized by a compiler to the "rotate" assembly language instruction on CPUs that have such an instruction. Most C compilers recognize the following idiom, and compile it to a single 32-bit rotate instruction.[1][2]

/*
 * Shift operations in C are only defined for shift values which are
 * not negative and smaller than sizeof(value) * CHAR_BIT.
 * The mask, used with bitwise-and (&), prevents undefined behaviour
 * when the shift count is 0 or >= the width of unsigned int.
 */

#include <stdint.h>  // for uint32_t, to get 32-bit-wide rotates, regardless of the size of int.
#include <limits.h>  // for CHAR_BIT

uint32_t rotl32 (uint32_t value, unsigned int count) {
    const unsigned int mask = CHAR_BIT * sizeof(value) - 1;
    count &= mask;
    return (value << count) | (value >> (-count & mask));
}

uint32_t rotr32 (uint32_t value, unsigned int count) {
    const unsigned int mask = CHAR_BIT * sizeof(value) - 1;
    count &= mask;
    return (value >> count) | (value << (-count & mask));
}

This safe and compiler-friendly implementation was developed by John Regehr,[3] and further polished by Peter Cordes.[4][5]

A simpler version is often seen when the count is limited to the range of 1 to 31 bits:

uint32_t rotl32 (uint32_t value, unsigned int count) {
    return (value << count) | (value >> (32 - count));
}

This version is dangerous because if the count is 0 or 32, it asks for a 32-bit shift, which is undefined behaviour in the C language standard. However, it tends to work anyway, because most microprocessors implement value >> 32 as either a 32-bit shift (producing 0) or a 0-bit shift (producing the original value), and either one produces the correct result in this application.

Example

If the bit sequence 0001 0111 were subjected to a circular shift of one bit position... (see images below)

  • to the left would yield: 0010 1110
Left circular shift.
  • to the right would yield: 1000 1011.
Right circular shift.

If the bit sequence 1001 0110 were subjected to the following operations:

left circular shift by 1 position: 0010 1101            
left circular shift by 2 positions: 0101 1010
left circular shift by 3 positions: 1011 0100
left circular shift by 4 positions: 0110 1001
left circular shift by 5 positions: 1101 0010
left circular shift by 6 positions: 1010 0101
left circular shift by 7 positions: 0100 1011
left circular shift by 8 positions: 1001 0110
right circular shift by 1 position: 0100 1011
right circular shift by 2 positions: 1010 0101
right circular shift by 3 positions: 1101 0010
right circular shift by 4 positions: 0110 1001
right circular shift by 5 positions: 1011 0100
right circular shift by 6 positions: 0101 1010
right circular shift by 7 positions: 0010 1101
right circular shift by 8 positions: 1001 0110

Applications

Cyclic codes are a kind of block code with the property that the circular shift of a codeword will always yield another codeword. This motivates the following general definition: For a string s over an alphabet Σ, let shift(s) denote the set of circular shifts of s, and for a set L of strings, let shift(L) denote the set of all circular shifts of strings in L. If L is a cyclic code, then shift(L) ⊆ L; this is a necessary condition for L being a cyclic language. The operation shift(L) has been studied in formal language theory. For instance, if L is a context-free language, then shift(L) is again context-free.[6][7] Also, if L is described by a regular expression of length n, there is a regular expression of length O(n3) describing shift(L).[8]

See also

References

  1. ^ GCC: "Optimize common rotate constructs"
  2. ^ "Cleanups in ROTL/ROTR DAG combiner code" mentions that this code supports the "rotate" instruction in the CellSPU
  3. ^ Safe, Efficient, and Portable Rotate in C/C++
  4. ^ Stackoverflow: Best practices for rotates in C/C++
  5. ^ Near constant time rotate that does not violate the standards
  6. ^ T. Oshiba, "Closure property of the family of context-free languages under the cyclic shift operation", Transactions of IECE, 55D:119–122, 1972.
  7. ^ A. N. Maslov, "Cyclic shift operation for languages", Problems of Information Transmission 9:333–338, 1973.
  8. ^ Gruber, Hermann; Holzer, Markus (2009). "Language operations with regular expressions of polynomial size" (PDF). Theoretical Computer Science. 410 (35): 3281–3289. doi:10.1016/j.tcs.2009.04.009. Zbl 1176.68105. Archived from the original (PDF) on 2017-08-29. Retrieved 2012-09-06..

Read other articles:

El Torneo de Amersfoort o Abierto de los Países Bajos fue un torneo oficial de tenis que se disputaba en la ciudad de Amersfoort, Países Bajos, dentro del calendario de la ATP. Era el torneo más tradicional en los Países Bajos y se jugaba sobre tierra batida desde la temporada 1957 (se jugó en canchas duras en algunas ocasiones, en la Era Abierta entre 1969 y 1972), aunque solamente desde el 2002 se jugó en esta ciudad. Anteriormente el torneo se jugó en las ciudades de Ámsterdam e Hi...

Кегичівський район адміністративно-територіальна одиниця Герб Прапор Район на карті Харківська область Основні дані Країна:  Україна Область: Харківська область Код КОАТУУ: 6323100000 Утворений: 1923 Населення: ▼ 21 013 (на 1.02.2016) Площа: 782 км² Густота: 26.9 осіб/км² Тел. код: +...

وادي كاغيان    خريطة الموقع سميت باسم نهر كاغيان  تقسيم إداري البلد الفلبين  [1] العاصمة تيغيغيوراو التقسيم الأعلى الفلبين  خصائص جغرافية إحداثيات 17°37′00″N 121°43′00″E / 17.616666666667°N 121.71666666667°E / 17.616666666667; 121.71666666667  [2] المساحة 28,228.83 كيلومتر مربع ...

Мапа НАТО у Європі   Члени НАТО   Підписано протокол приєднання   План дій щодо членства в НАТО   Партнерство із розширеними можливостями   Індивідуальний партнерський план   Партнерство заради миру   Члени на вступ до програми Партнер...

Сухиницький район рос. Сухиничский район Герб Прапор Адм. центр Сухиничі Країна  Росія Область Калузька область Населення  - повне 24029  - густота 21,8 Площа  - повна 1232 км² Дата заснування 1929 Вебсайт suhinichi-admin.ru Вікісховище має мультимедійні даніза темою: Сухиницьк

Academic discipline comparing literature across cultures This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (November 2010) (Learn how and when to remove this template message) Literature Oral literature Folklore Fable Fairy tale Folk play Folksong Heroic epic Legend Myth Proverb Oration Performance Audiobook Spoken word Saying Major written forms Drama Closet dr...

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

1983 film by John Korty Twice Upon a TimeTheatrical release posterDirected byJohn KortyCharles SwensonWritten byJohn KortyCharles SwensonSuella KennedyBill CouturiéProduced byBill CouturiéStarringLorenzo MusicJulie PayneJames CrannaHamilton CampMarshall EfronJudith Kahan KampmannNarrated byPaul FreesEdited byJennifer GallagherMusic byKen MelvilleDawn Atkinson[1]ProductioncompaniesKorty FilmsLucasfilmDistributed byThe Ladd Company(through Warner Bros.)Release date August 5, ...

Lilium speciosum Біологічна класифікація Царство: Рослини (Plantae) Клада: Судинні рослини (Tracheophyta) Клада: Покритонасінні (Angiosperms) Клада: Однодольні (Monocotyledon) Порядок: Лілієцвіті (Liliales) Родина: Лілієві (Liliaceae) Підродина: Lilioideae Триба: Lilieae Рід: Лілія (Lilium) Вид: L. speciosum Біноміальна назва Lili...

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Oktober 2016. Methanosarcina acetivorans C2A Klasifikasi ilmiah Domain: Archaea Kerajaan: Euryarchaeota Filum: Euryarchaeota Kelas: Methanomicrobia Ordo: Methanosarcinales Famili: Methanosarcinaceae Genus: Methanosarcina Spesies: M. acetivorans Nama binomial Me...

La ley 15.848 de Caducidad de la Pretensión Punitiva del Estado (popularmente conocida como Ley de Caducidad y llamada peyorativamente Ley de Impunidad por sus detractores),[1]​[2]​[3]​[4]​ es una ley dictada en Uruguay en 1986 mediante la cual se estableció la caducidad del ejercicio de la pretensión punitiva del Estado respecto de los delitos cometidos hasta el 1º de marzo de 1985 por funcionarios militares y policiales, equiparados y asimilados por móviles pol...

Aku Titipkan CintaGenre Drama Roman PembuatTobali Putra ProductionsDitulis olehTeam TobaliSutradaraSondang PratamaPemeran Rezky Adhitya Citra Kirana Ari Wibowo Barry Prima Ira Wibowo Penggubah lagu temaTri SuakaLagu pembukaAku Bukan Jodohnya — Tri SuakaLagu penutupAku Bukan Jodohnya — Tri SuakaPenata musikMatthews SiahaanNegara asalIndonesiaBahasa asliBahasa IndonesiaJmlh. musim1Jmlh. episode50ProduksiProduser eksekutifUtojo SutjiutamaProduserFerry FernandezLokasi produksiJakarta, I...

Palazzo BorromeoFacade of the palace in Piazza BorromeoPalazzo BorromeoShow map of MilanPalazzo BorromeoShow map of ItalyGeneral informationArchitectural stylelate GothicTown or cityMilanCountryItalyCoordinates45°27′48″N 9°10′56″E / 45.4634°N 9.1822°E / 45.4634; 9.1822OwnerBorromeo family Palazzo Borromeo (Borromeo Palace) is a 13th-century building located at street #12 of Piazza Borromeo in Milan, region of Lombardy, Italy, . It stands across a small piaz...

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Maret 2016. SMAN 1 DAPURANGInformasiJurusan atau peminatanIPA dan IPSRentang kelasX, XI IPA, XI IPS, XII IPA, XII IPSKurikulumKurikulum Tingkat Satuan PendidikanAlamatLokasiJl. Trans sulawesi Dapurang, Sulawesi BaratMoto 'SMA Negeri (SMAN) 1 Dapurang/SMA Negeri 6 Pa...

Wasserstraßen- und Schifffahrtsamt Emden(WSA Emden) Staatliche Ebene Bund Stellung Unterbehörde Aufsichtsbehörde Generaldirektion Wasserstraßen und Schifffahrt Gründung 1949 Auflösung 15. Januar 2020 Nachfolger WSA Ems-Nordsee Hauptsitz Emden Das Wasserstraßen- und Schifffahrtsamt Emden (WSA Emden) war ein Wasserstraßen- und Schifffahrtsamt in Deutschland. Es gehörte zum Dienstbereich der Generaldirektion Wasserstraßen und Schifffahrt, vormals Wasser- und Schifffahrtsdirektion Nordw...

American politician Daniel G. Taylor17th Mayor of St. Louis, MissouriIn office1861–1863Preceded byOliver FilleySucceeded byChauncey Filley Personal detailsBorn(1819-11-15)November 15, 1819Cincinnati, Ohio, USDiedOctober 8, 1878(1878-10-08) (aged 58)St. Louis, Missouri, USResting placeCalvary CemeteryPolitical partyUnion Anti-Black Republican Daniel G. Taylor (November 15, 1819 – October 8, 1878) was the 17th mayor of St. Louis, Missouri, serving from 1861 to 1863. Early life Taylor w...

You can help expand this article with text translated from the corresponding article in Polish. (October 2016) Click [show] for important translation instructions. View a machine-translated version of the Polish article. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wikipe...

在亞美尼亞設有外交機構的國家 此列表羅列各國駐亞美尼亞的外交代表機構,這些機構部分位於亞美尼亞境外。 位於亞美尼亞境內的外交機構 德國駐亞美尼亞大使館 希臘駐亞美尼亞大使館 俄羅斯駐亞美尼亞大使館 國家 雙邊關係 機構性質 所在地 參考資料  阿根廷 阿根廷-亞美尼亞關係 大使館 埃里溫 [1]  奥地利 亞美尼亞-奧地利關係 辦事處 埃里溫 [2]...

Sint-Bartholomeuskerk De Sint-Bartholomeuskerk is de parochiekerk van de tot de West-Vlaamse gemeente Zuienkerke behorende plaats Nieuwmunster, gelegen aan de Doelhofstraat. Geschiedenis De kerk zou zijn gesticht door de Tempeliers die het gebied in 1128 zouden hebben gekregen van graaf Diederik van de Elzas, hiervan zijn echter geen harde bewijzen. De kerk zou zijn bediend door Augustijnen van het Brugse Eekhoutabdij, eveneens aan Sint-Bartholomeus gewijd. De parochie werd voor het eerst sch...

Сервер HP ProLiant 380 G5 ProLiant — торговая марка серверов, разработанных и распространявшихся фирмой Compaq с осени 1993 года[1]. Линейка сменила предыдущий бренд серверов верхнего сегмента от Compaq — SystemPro XL. После поглощения корпорацией Hewlett-Packard марка сохранена и развивается...