• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why is this AND operation necessary?  RSS feed

 
Marie Day
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The purpose of this code is to store two bytes of a short sequentially in the buffer.
Why does this have to be an AND operation?

Couldn't you just cast short ss as a byte? The significant byte would be cut off, and the
other byte would be stored in the buffer, wouldn't it, without needing the AND operation?

I must be missing something. Code below.

This code is from
http://www.drdobbs.com/jvm/music-components-in-java-creating-oscill/230500178

 
Carey Brown
Bartender
Posts: 3011
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'ss' is a short which takes two bytes of storage, 0xFF has 1 byte's worth of bits turned on (1111 1111), doing a bit wise AND then keeps only the least significant byte of the two bytes of the short.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marie Day wrote:Couldn't you just cast short ss as a byte? The significant byte would be cut off, and the
other byte would be stored in the buffer, wouldn't it, without needing the AND operation?

I must be missing something.

You are right, the AND operation to keep only the lower 8 bits of the short is not necessary, because casting a short to a byte already does this. So it could just have been:


Maybe the programmer who wrote this didn't understand this properly.
 
Henry Wong
author
Sheriff
Posts: 23284
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote:
Maybe the programmer who wrote this didn't understand this properly.


Or perhaps, it is done for consistency. For example, to go from short to byte, you need the explicit cast, but not the AND operation. And to go from byte to short, you don't need the explicit cast, but you do need the AND operation... perhaps, it is just easier to make sure that each conversion has the cast and masking of bits, regardless whether it is needed or not.

Regardless, it is an interesting catch, and cow-worthy. Have a cow...

Henry
 
Marie Day
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thanks for the cow, and clarification.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!