SlideShare a Scribd company logo
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

More Related Content

What's hot

Logarithm
LogarithmLogarithm
Logarithm
Febri Arianti
 
Slides2if85 assmeth2
Slides2if85 assmeth2Slides2if85 assmeth2
Slides2if85 assmeth2
mackees
 
Bt0069 discrete mathematics
Bt0069   discrete mathematicsBt0069   discrete mathematics
Bt0069 discrete mathematics
smumbahelp
 
Applications of Linear Algebra
Applications of Linear AlgebraApplications of Linear Algebra
Applications of Linear Algebra
Naveenchandra Halemani
 
Automata
AutomataAutomata
Automata
Gaditek
 
5 6 laws of logarithms
5 6 laws of logarithms5 6 laws of logarithms
5 6 laws of logarithmshisema01
 
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
Vivekananda Samiti
 
Deep learning book_chap_02
Deep learning book_chap_02Deep learning book_chap_02
Deep learning book_chap_02
HyeongGooKang
 
Theory of Computation Introduction Session
Theory of Computation Introduction SessionTheory of Computation Introduction Session
Theory of Computation Introduction Session
Rushabh2428
 
Reguler grammar cfg
Reguler grammar cfgReguler grammar cfg
Reguler grammar cfg
Dr. ABHISHEK K PANDEY
 
Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)
Animesh Chaturvedi
 
Abstract Algebra Cheat Sheet
Abstract Algebra Cheat SheetAbstract Algebra Cheat Sheet
Abstract Algebra Cheat SheetMoe Han
 
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
csandit
 
Flat unit 1
Flat unit 1Flat unit 1
Flat unit 1
VenkataRaoS1
 

What's hot (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
 

Similar to 04 Jo P Apr 07

論文紹介 Fast imagetagging
論文紹介 Fast imagetagging論文紹介 Fast imagetagging
論文紹介 Fast imagetaggingTakashi Abe
 
Unit 05 - Limits and Continuity.pdf
Unit 05 - Limits and Continuity.pdfUnit 05 - Limits and Continuity.pdf
Unit 05 - Limits and Continuity.pdf
SagarPetwal
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming hccit
 
Stochastic Processes Homework Help
Stochastic Processes Homework HelpStochastic Processes Homework Help
Stochastic Processes Homework Help
Excel Homework Help
 
Reasoning about laziness
Reasoning about lazinessReasoning about laziness
Reasoning about lazinessJohan Tibell
 
C language basics
C language basicsC language basics
C language basics
Milind Deshkar
 
Stochastic Processes Homework Help
Stochastic Processes Homework HelpStochastic Processes Homework Help
Stochastic Processes Homework Help
Statistics Homework Helper
 
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
Alireza Mirzaei
 
BASIC OF ALGORITHM AND MATHEMATICS STUDENTS
BASIC OF ALGORITHM AND MATHEMATICS STUDENTSBASIC OF ALGORITHM AND MATHEMATICS STUDENTS
BASIC OF ALGORITHM AND MATHEMATICS STUDENTS
jainyshah20
 
Index notation
Index notationIndex notation
Index notation
MERTEKMEN
 
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
Deepak John
 
Ee693 sept2014quizgt2
Ee693 sept2014quizgt2Ee693 sept2014quizgt2
Ee693 sept2014quizgt2
Gopi Saiteja
 
Binary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick TreeBinary Indexed Tree / Fenwick Tree
Binary Indexed Tree / Fenwick Tree
Mohammed Ashiqur Rahman Baig
 
GPUVerify - Implementation
GPUVerify - ImplementationGPUVerify - Implementation
GPUVerify - Implementation
gedgemaster
 
Math 8 - Linear Functions
Math 8 - Linear FunctionsMath 8 - Linear Functions
Math 8 - Linear Functions
Carlo Luna
 
clmath8q2w4linearfunctions-211212103328.pdf
clmath8q2w4linearfunctions-211212103328.pdfclmath8q2w4linearfunctions-211212103328.pdf
clmath8q2w4linearfunctions-211212103328.pdf
mysthicrious
 
UNIT_-_II.docx
UNIT_-_II.docxUNIT_-_II.docx
UNIT_-_II.docx
karthikeyan Muthusamy
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in JavaAbhilash Nair
 
Solution 1
Solution 1Solution 1
Solution 1aldrins
 
How to read a character table
How to read a character tableHow to read a character table
How to read a character table
sourabh muktibodh
 

Similar to 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
 

More from Ganesh Samarthyam

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
Ganesh Samarthyam
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
Ganesh Samarthyam
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
Ganesh Samarthyam
 
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”
Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
Ganesh Samarthyam
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
Ganesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
Ganesh Samarthyam
 
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
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
Ganesh Samarthyam
 
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)
Ganesh Samarthyam
 
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++
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
Ganesh Samarthyam
 
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
Ganesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
Ganesh Samarthyam
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
Ganesh Samarthyam
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
Ganesh Samarthyam
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
Ganesh Samarthyam
 
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
Ganesh Samarthyam
 

More from 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
 

Recently uploaded

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 

Recently uploaded (20)

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 

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