SlideShare une entreprise Scribd logo
1  sur  1
Télécharger pour lire hors ligne
The Joy of
Programming
How ‘C’mart Are You?
Some Bit-manipulation                                                                                                       S.G. GANESH




Tricks and Techniques
In this column, lets see few interesting bit-manipulation tips; such techniques are useful and
widely used in advanced low-level programming tasks such as writing software emulators
and device drivers.

It is assumed that the underlying implementation follows                       EXORing i with all 1s results in resetting the bits
2’s complement representation for integers.                                    that are set; so it’s the same as ~i!
     Assume that i, j and r are integers.                                      In ~i = -(i + 1) implies ~i = (-i -1). Move -1 to the left
Q1: What does the expression “(i & (i – 1))” do?                               side and the expression is: (~i + 1 = -i); now you can
A:      It checks if i is a power of 2 or not!                                 read it as “1’s complement of i plus 1 is 2’s




                                                                                                                                   GUEST COLUMN
Q2: What does the expression (i & (-i)) do?                                    complement of i”, which is correct!
A:      It returns the lowest bit set in an integer (which is a           Q 4: (j + ((i - j) & -(i < j)) – let’s read it as: With
        power of 2)!                                                           j (it can be i also), add the difference
Q3: How can you express ~i in terms of other (preferably                       between the two, and (re)set the sign bit
        bit-wise) operators?                                                   for the value of the difference between the
A:      (i ^ (~0)) and –(i + 1).                                               two. If j is less than i, the expression adds
Q4: What does the expression (j + ((i - j) & -(i < j)) do?                     the difference between the two; or else it
A:      This code results in the maximum of two integers i                     subtracts the difference between the two.
        and j.                                                                 Following the same logic (j - ((i - j) & -(i <
Q5: How can you express the expression (i + j) in terms                        j)) is the minimum of i and j.
        of bit-wise ‘&’ and ‘|’ operations?                               Q 5: (i | j) sets the bits that are only set in either
A:      ((i & j) + (i | j))                                                    i or j. (i & j) shows the value that’s set in
Q6: What is the significance of the expression r = (i ^ j ^                    both the values. Adding these two results
        r)?                                                                    has the effect of retaining the bits set, the
A:      If r is equal to i, r will be reset to j; else if r is equal to        bits set. Then adding the bits set in both the
        j, r will be reset to i!                                               values again with the result, if you closely
                                                                               observe, is the same as, it is the same as
That’s enough; let’s see the explanation.                                      (i + j).
Q1.  When i is a value that’s a power of 2, only a single bit             Q 6: If r is equal to i, it will nullify the effect of it
     will be set in that integer. Now, when you subtract 1                     in the expression (i ^ j ^ r) resulting in j;
     from that value, that bit will be reset and will result                   the same happens if r is equal to j. (This is the same
     in setting the lower bits. For (i & (i – 1)), when it is a                trick used to re-write a doubly linked list—with
     power of 2, the resulting two bit patterns will have                      previous and next pointers—with a single pointer,
     no common bits set, so the expression becomes false                       which has the EXORed result of the previous and
     (in that case it’s a power of 2); else it isn’t.                          next pointers!)
Q 2: -i is 1’s complement of i plus 1; when you invert all
     the bits in an integer and add 1 to it, all the set bits              S.G. Ganesh is an engineer in Hewlett-Packard’s C++
     in the end are reset to zero. When we do ‘&’ of these                 compiler team. He has authored a book “Deep C” (ISBN 81-
     two values, we get only the lowest bit set (since all                 7656-501-6). He is also a member of the ANSI/ISO C++
     other bits will have complementary values set in                      Standardisation committee (JTC1/SC22/WG21),
                                                                           representing HP. You can reach him at
     them).
                                                                           sgganesh@gmail.com.
Q 3: ~i is 1’s complement of i; since ~0 is all 1’s set and


                                                                                www.linuxforu.com   |   LINUX FOR YOU   |    APRIL 2007   73


                                                                  CMYK

Contenu connexe

Tendances

5 6 laws of logarithms
5 6 laws of logarithms5 6 laws of logarithms
5 6 laws of logarithms
hisema01
 
Abstract Algebra Cheat Sheet
Abstract Algebra Cheat SheetAbstract Algebra Cheat Sheet
Abstract Algebra Cheat Sheet
Moe Han
 

Tendances (20)

Logarithm
LogarithmLogarithm
Logarithm
 
Slides2if85 assmeth2
Slides2if85 assmeth2Slides2if85 assmeth2
Slides2if85 assmeth2
 
Logarithms
LogarithmsLogarithms
Logarithms
 
Bt0069 discrete mathematics
Bt0069   discrete mathematicsBt0069   discrete mathematics
Bt0069 discrete mathematics
 
Applications of Linear Algebra
Applications of Linear AlgebraApplications of Linear Algebra
Applications of Linear Algebra
 
Automata
AutomataAutomata
Automata
 
5 6 laws of logarithms
5 6 laws of logarithms5 6 laws of logarithms
5 6 laws of logarithms
 
End semexam | Theory of Computation | Akash Anand | MTH 401A | IIT Kanpur
End semexam | Theory of Computation | Akash Anand | MTH 401A | IIT KanpurEnd semexam | Theory of Computation | Akash Anand | MTH 401A | IIT Kanpur
End semexam | Theory of Computation | Akash Anand | MTH 401A | IIT Kanpur
 
Deep learning book_chap_02
Deep learning book_chap_02Deep learning book_chap_02
Deep learning book_chap_02
 
Unit 1. day 6b
Unit 1. day 6bUnit 1. day 6b
Unit 1. day 6b
 
Theory of Computation Introduction Session
Theory of Computation Introduction SessionTheory of Computation Introduction Session
Theory of Computation Introduction Session
 
Reguler grammar cfg
Reguler grammar cfgReguler grammar cfg
Reguler grammar cfg
 
Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)
 
AI Lesson 15
AI Lesson 15AI Lesson 15
AI Lesson 15
 
F-Compact operator1_p1-2
F-Compact operator1_p1-2F-Compact operator1_p1-2
F-Compact operator1_p1-2
 
Logic agent
Logic agentLogic agent
Logic agent
 
Abstract Algebra Cheat Sheet
Abstract Algebra Cheat SheetAbstract Algebra Cheat Sheet
Abstract Algebra Cheat Sheet
 
ANOTHER PROOF OF THE DENUMERABILITY OF THE COMPLEX NUMBERS
ANOTHER PROOF OF THE DENUMERABILITY OF THE COMPLEX NUMBERSANOTHER PROOF OF THE DENUMERABILITY OF THE COMPLEX NUMBERS
ANOTHER PROOF OF THE DENUMERABILITY OF THE COMPLEX NUMBERS
 
Recursion DM
Recursion DMRecursion DM
Recursion DM
 
Flat unit 1
Flat unit 1Flat unit 1
Flat unit 1
 

Similaire à 04 Jo P Apr 07

論文紹介 Fast imagetagging
論文紹介 Fast imagetagging論文紹介 Fast imagetagging
論文紹介 Fast imagetagging
Takashi Abe
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming
hccit
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
Johan Tibell
 
BASIC OF ALGORITHM AND MATHEMATICS STUDENTS
BASIC OF ALGORITHM AND MATHEMATICS STUDENTSBASIC OF ALGORITHM AND MATHEMATICS STUDENTS
BASIC OF ALGORITHM AND MATHEMATICS STUDENTS
jainyshah20
 
clmath8q2w4linearfunctions-211212103328.pdf
clmath8q2w4linearfunctions-211212103328.pdfclmath8q2w4linearfunctions-211212103328.pdf
clmath8q2w4linearfunctions-211212103328.pdf
mysthicrious
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
Abhilash Nair
 
Solution 1
Solution 1Solution 1
Solution 1
aldrins
 

Similaire à 04 Jo P Apr 07 (20)

論文紹介 Fast imagetagging
論文紹介 Fast imagetagging論文紹介 Fast imagetagging
論文紹介 Fast imagetagging
 
Unit 05 - Limits and Continuity.pdf
Unit 05 - Limits and Continuity.pdfUnit 05 - Limits and Continuity.pdf
Unit 05 - Limits and Continuity.pdf
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming
 
Stochastic Processes Homework Help
Stochastic Processes Homework HelpStochastic Processes Homework Help
Stochastic Processes Homework Help
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about laziness
 
C language basics
C language basicsC language basics
C language basics
 
Stochastic Processes Homework Help
Stochastic Processes Homework HelpStochastic Processes Homework Help
Stochastic Processes Homework Help
 
How to design a linear control system
How to design a linear control systemHow to design a linear control system
How to design a linear control system
 
BASIC OF ALGORITHM AND MATHEMATICS STUDENTS
BASIC OF ALGORITHM AND MATHEMATICS STUDENTSBASIC OF ALGORITHM AND MATHEMATICS STUDENTS
BASIC OF ALGORITHM AND MATHEMATICS STUDENTS
 
Index notation
Index notationIndex notation
Index notation
 
Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1
 
Ee693 sept2014quizgt2
Ee693 sept2014quizgt2Ee693 sept2014quizgt2
Ee693 sept2014quizgt2
 
Binary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick TreeBinary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick Tree
 
GPUVerify - Implementation
GPUVerify - ImplementationGPUVerify - Implementation
GPUVerify - Implementation
 
Math 8 - Linear Functions
Math 8 - Linear FunctionsMath 8 - Linear Functions
Math 8 - Linear Functions
 
clmath8q2w4linearfunctions-211212103328.pdf
clmath8q2w4linearfunctions-211212103328.pdfclmath8q2w4linearfunctions-211212103328.pdf
clmath8q2w4linearfunctions-211212103328.pdf
 
UNIT_-_II.docx
UNIT_-_II.docxUNIT_-_II.docx
UNIT_-_II.docx
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
 
Solution 1
Solution 1Solution 1
Solution 1
 
How to read a character table
How to read a character tableHow to read a character table
How to read a character table
 

Plus de Ganesh Samarthyam

Plus de Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

04 Jo P Apr 07

  • 1. The Joy of Programming How ‘C’mart Are You? Some Bit-manipulation S.G. GANESH Tricks and Techniques In this column, lets see few interesting bit-manipulation tips; such techniques are useful and widely used in advanced low-level programming tasks such as writing software emulators and device drivers. It is assumed that the underlying implementation follows EXORing i with all 1s results in resetting the bits 2’s complement representation for integers. that are set; so it’s the same as ~i! Assume that i, j and r are integers. In ~i = -(i + 1) implies ~i = (-i -1). Move -1 to the left Q1: What does the expression “(i & (i – 1))” do? side and the expression is: (~i + 1 = -i); now you can A: It checks if i is a power of 2 or not! read it as “1’s complement of i plus 1 is 2’s GUEST COLUMN Q2: What does the expression (i & (-i)) do? complement of i”, which is correct! A: It returns the lowest bit set in an integer (which is a Q 4: (j + ((i - j) & -(i < j)) – let’s read it as: With power of 2)! j (it can be i also), add the difference Q3: How can you express ~i in terms of other (preferably between the two, and (re)set the sign bit bit-wise) operators? for the value of the difference between the A: (i ^ (~0)) and –(i + 1). two. If j is less than i, the expression adds Q4: What does the expression (j + ((i - j) & -(i < j)) do? the difference between the two; or else it A: This code results in the maximum of two integers i subtracts the difference between the two. and j. Following the same logic (j - ((i - j) & -(i < Q5: How can you express the expression (i + j) in terms j)) is the minimum of i and j. of bit-wise ‘&’ and ‘|’ operations? Q 5: (i | j) sets the bits that are only set in either A: ((i & j) + (i | j)) i or j. (i & j) shows the value that’s set in Q6: What is the significance of the expression r = (i ^ j ^ both the values. Adding these two results r)? has the effect of retaining the bits set, the A: If r is equal to i, r will be reset to j; else if r is equal to bits set. Then adding the bits set in both the j, r will be reset to i! values again with the result, if you closely observe, is the same as, it is the same as That’s enough; let’s see the explanation. (i + j). Q1. When i is a value that’s a power of 2, only a single bit Q 6: If r is equal to i, it will nullify the effect of it will be set in that integer. Now, when you subtract 1 in the expression (i ^ j ^ r) resulting in j; from that value, that bit will be reset and will result the same happens if r is equal to j. (This is the same in setting the lower bits. For (i & (i – 1)), when it is a trick used to re-write a doubly linked list—with power of 2, the resulting two bit patterns will have previous and next pointers—with a single pointer, no common bits set, so the expression becomes false which has the EXORed result of the previous and (in that case it’s a power of 2); else it isn’t. next pointers!) Q 2: -i is 1’s complement of i plus 1; when you invert all the bits in an integer and add 1 to it, all the set bits S.G. Ganesh is an engineer in Hewlett-Packard’s C++ in the end are reset to zero. When we do ‘&’ of these compiler team. He has authored a book “Deep C” (ISBN 81- two values, we get only the lowest bit set (since all 7656-501-6). He is also a member of the ANSI/ISO C++ other bits will have complementary values set in Standardisation committee (JTC1/SC22/WG21), representing HP. You can reach him at them). sgganesh@gmail.com. Q 3: ~i is 1’s complement of i; since ~0 is all 1’s set and www.linuxforu.com | LINUX FOR YOU | APRIL 2007 73 CMYK