• Post Reply Bookmark Topic Watch Topic
  • New Topic

Application of shifting operators  RSS feed

 
Jon Camilleri
Ranch Hand
Posts: 664
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you have an example where the following operators are useful?

<<= i.e. signed left shift and add to result
>>= i.e. signed right shift and add to result
>>>= i.e. unsigned right shift and add to result

Sources
1. Summary of Operators, available at http://download.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
2. Java Language Specification 3rd Edition, available at http://java.sun.com/docs/books/jls/third_edition/html/syntax.html#18.1.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In practice they can be useful for many different things.

In fact, I'm working on a system right now that has to communicate with several different devices that use some specific, proprietary protocols. The specifications of the protocols explain exactly what bytes you have to send to the device in what format, and what bytes the device sends back. My Java program has to parse and format messages for these devices in exactly the right format.

So, the specifications for example say that a message is prefixed with some bytes that indicate how many bytes of data there are in the message, but those length bytes are encoded in a very specific way: bit 7 of each byte is set to 1 if there is another length byte, it it set to 0 if this is the last length byte, and bits 6-0 contain part of the length value. Calculating the exact length value requires using bitwise operators (& and |) and shift operators.
 
Jon Camilleri
Ranch Hand
Posts: 664
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote:In practice they can be useful for many different things.

In fact, I'm working on a system right now that has to communicate with several different devices that use some specific, proprietary protocols. The specifications of the protocols explain exactly what bytes you have to send to the device in what format, and what bytes the device sends back. My Java program has to parse and format messages for these devices in exactly the right format.

So, the specifications for example say that a message is prefixed with some bytes that indicate how many bytes of data there are in the message, but those length bytes are encoded in a very specific way: bit 7 of each byte is set to 1 if there is another length byte, it it set to 0 if this is the last length byte, and bits 6-0 contain part of the length value. Calculating the exact length value requires using bitwise operators (& and |) and shift operators.


Thank you, is it possible to post some sample code?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!