Main Site Documentation

Bitwise AND operator for Bit Masking


#1

Hi,
Quick question - is there a way to do & in .netmf? Can’t seem to find it. Basically I’m reading a value using i2c which will return a byte, where the 4 LSF is what I’m after, and 4MSF are just settings I don’t want included in my reading, so I wish to mask them out.

Also, any way to convert something easily to a binary string? Basically right now I’m getting output like “65”, instead id much rather have the debug print 01000001.


#2

Bitwise & is there.


#3

Check this project they have some string extensions and they might have binary output

Check this thread:

http://www.tinyclr.com/forum/1/1589/

There is a code example that uses bitwise operations.


#4

When I try it I get “Cannot convert int to byte”

            byte NumberToMask = 54;
            byte mask = 43;
            byte Masked = NumberToMask & mask;

I can’t work out where its working with an integer, so whats wrong?


#5

That is because the result of a bitwise AND is an integer. You need to cast it to byte.

Remember this is C#, so the majority of regular old C# syntax applies…


            byte NumberToMask = 54;
            byte mask = 43;
            byte Masked = (byte)(NumberToMask & mask);


#6

Thanks, the error message was confusing, I would expect it to be quoted the other way around. And well, I’m happy to see that C# rules apply, however I’ve never programmed in C# before - I’m attempting to apply a mix of Java and C rules here :slight_smile:

Cheers for the help,
PS I’m trying to write a DS1307 driver, hopefully will have it done soon, that ll be my first post to fezzer


#7

I have one small suggestion: write constants used for bitwise operations in hex. It is much easier/faster to find which bits are ‘in scope’ as eatch hex digit represents 4 bits - quite easy.
When I see 54 - it takes a lot of time to convert it to proper bits. When you see 0x36 (the same value) it is clear-> 0011 0110…


#8

Xarren, anything you don’t like in the driver I wrote for the DS1307: http://www.fezzer.com/project/30/rtc1307/ ?


#9

Noo It’s not that I don’t like anything in it, its just that while I don’t fully understand the language and framework, I can learn a lot by doing the basics. If I just use yours, and run into a device not on fezzer already, I won’t have a clue how to approach it. Anyways I got it mostly working now, just slightly issues with some of the data being lost somewhere, every 20 or so seconds, but Ill get ontop of it