Home arrow static arrow Java Programming [Archive] - My mask doesn't work for reading bits
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - My mask doesn't work for reading bits
This topic has 13 replies on 1 page.

Posts:343
Registered: 7/13/04
My mask doesn't work for reading bits  
Jul 13, 2004 9:57 AM



 
the following table represents a stream of bits. within the bits are certain fields that i need to be able to read, and extract. I tried writing code to do pretty much exactly what I need, but the mask isn't working. here is the exact situation of what I have:

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0


|-----------------Word Count--------------------------------------| word 1

| 0- | 1-- |-------------Message_ID------|----unused---------| word 2

|---------------------stuff I don't care about here -------------| word 3

|
more stuff I don't care about here ---------| word 4


My goal in writing this code was to extract the Message_ID and put it in its own file. to do that I wrote code to skip the first word (which is two bytes) and read the second word after shifting the Message_ID to the far right (at least thats what I thought the coding would do :) Again, thank you for all your guys' help

well here is the short java file that I wrote, its not long so please look at it and tell me why it wont mask and shift the Message_ID and write it into a new file

import java.io.*;

public class Mask {
public static void main(String[] arguments) {
try {
// create object to be read
File bits = new File("c:/test.txt");
FileInputStream file = new FileInputStream(bits);

//skip the first two bytes
file.skip(2);

//read the next two bytes
byte[] ary = new byte[2];

//read file that contains bits
file.read(ary);

//create a mask
int i = 0;
int messageIDBits = (i >> 6) & 0xFF;

//create object to write the bits which were read
File txt = new File("c:/test1.txt");
FileOutputStream messageID = new FileOutputStream(txt);

//write the bits containing the Message_ID
messageID.write(ary);

//close the files
file.close();
messageID.close();

} catch (Exception e) {
System.out.println("Error -- " + e.toString());
}

}
}

 

Posts:24,036
Registered: 2/3/03
Re: My mask doesn't work for reading bits  
Jul 13, 2004 10:17 AM (reply 1 of 13)



 
When do you use the mask?
 

Posts:343
Registered: 7/13/04
Re: My mask doesn't work for reading bits  
Jul 13, 2004 10:26 AM (reply 2 of 13)



 
well, I'm just learning how to use masks, if you could help me I would appreciate it. I thought the mask is being used where I set up the variable. How would I need to modify the program to use the mask?
 

Posts:24,036
Registered: 2/3/03
Re: My mask doesn't work for reading bits  
Jul 13, 2004 10:36 AM (reply 3 of 13)



 
How would I need to modify the program to use the mask?

int i = 0;int messageIDBits = (i >> 6) & 0xFF;

Right-shifting an int value of '0' isn't going to do much; you'll be left with '0'. Then, &-*** them with 0xFF will also give you a '0' result. In addition, you're not modifying the bytes that contain the Message_ID. I'll cook up an example, but in the meantime, check the following resources...

[url=http://www.javaranch.com/camp/StoryBits.jsp]Cat and Mouse Games with Bits[/url]
[url=http://java.sun.com/docs/books/tutorial/java/nutsandbolts/bitwise.html]Java Tutorial: Shift and Logical Operators[/url]
 

Posts:343
Registered: 7/13/04
Re: My mask doesn't work for reading bits  
Jul 13, 2004 10:42 AM (reply 4 of 13)



 
I wasn't really sure what the int i = 0; does, i thought that i was shifting the Message_ID to the right 6 spaces. i'll be waiting for you to look up whatever will help me, thank you in advance for your help
 

Posts:4,130
Registered: 3/31/99
Re: My mask doesn't work for reading bits  
Jul 13, 2004 10:46 AM (reply 5 of 13)



 
If I understand correctly, Message_ID is 8 bits long and sits between bits 13 and 6 inclusive. So the binary mask is 11111111 (or 255 decimal). You just need to take Word 2, shift it right 6 times and & with 255. Right now you code takes the variable i, whose value is zero and shifts it right 6 times.
 

Posts:24,036
Registered: 2/3/03
Re: My mask doesn't work for reading bits  
Jul 13, 2004 10:48 AM (reply 6 of 13)



 
i'll be waiting for you to look up
whatever will help me...

Erm, no. Don't wait - go out and research this yourself. Read the links I provided. And if you don't know what "int i = 0;" does, you'll need to start with some foundations before you continue. I recommend the following:

http://java.sun.com/docs/books/tutorial/
http://java.sun.com/learning/new2java/index.html
http://javaalmanac.com
http://www.jguru.com
http://www.javaranch.com
Bruce Eckel's [url=http://mindview.net/Books/DownloadSites]Thinking in Java[/url]
Joshua Bloch's [url=http://www.amazon.co.uk/exec/obidos/Author=Bloch,%20Josh]Effective Java[/url]
Bert Bates and Kathy Sierra's [url=http://www.amazon.com/exec/obidos/tg/detail/-/0596004656?v=glance]Head First Java[/url]

I'll try to give you an example, but I'm not going to be able to look up information for you.
 

Posts:343
Registered: 7/13/04
Re: My mask doesn't work for reading bits  
Jul 13, 2004 11:04 AM (reply 7 of 13)



 
sorry, i didn't literally mean wait for you to do this FOR me. i've been researching, looking at links and so forth. I wanted to do as much of this as possible on my own, but i just couldn't get that mask to work. that webpage you gave me is awsome, i now know what the letter before the >> operator does, and i feel like i understand how masking works. I just can't seem to get it right. one change i've tried in my program is the following:

//create a mask
int messageIDBits = (ary >> 6) & 0xFF;

this doesn't work becasue it does not like the fact that there is an array there.
I also tried this:

//create a mask
int messageIDBits = (0x3FC0 >> 6) & 0xFF; // 3FC0 is the hex that represents 1's in bits 13-6, and 0's in bits 5-0
 

Posts:343
Registered: 7/13/04
Re: My mask doesn't work for reading bits  
Jul 13, 2004 12:32 PM (reply 8 of 13)



 
so, can anyone help me? how do i get word 2 to shift so that I can read the Message_ID?
 

Posts:24,036
Registered: 2/3/03
Re: My mask doesn't work for reading bits  
Jul 13, 2004 12:35 PM (reply 9 of 13)



 
Sorry it took so long - had a meeting. Here's the demo. Run it, study it, and let me know if you have any questions:
import java.io.*;import java.util.*; class BytesDemo {     private static Random rand = new Random();     public static void main(String[] args) {        new BytesDemo().go();    }     void go() {        byte[] testBytes = new byte[2];        rand.nextBytes(testBytes);        System.out.println("Here are our starting bytes (" +                            testBytes[0] + ", " +                            testBytes[1] + "):");        System.out.println(toBinary(testBytes[0], 8) +                         " " +                         toBinary(testBytes[1], 8));         System.out.println("\nNow, we'll call the getMessageId() method...");         int messageId = getMessageId(testBytes);        System.out.println("\nOur final message ID is: \n" + messageId);         System.out.println("\nAnd here's the short version: " + getId(testBytes));    }     int getMessageId(byte[] b) {        if (b.length != 2) throw new IllegalArgumentException("I need two bytes!");         System.out.println("\nFirst, we'll create the word.");        System.out.println("Here is the first byte, shifted to the left: \n" +                           toBinary(b[0] << 8, 16));         System.out.println("\nHere is the second byte, kept as it is: \n" +                           toBinary(b[1] & 0xFF, 16));         System.out.println("\nNow we will OR the two together...");        int word = (b[0] << 8) | (b[1] & 0xFF);         System.out.println("...resulting in the word: \n" + toBinary(word, 16));         System.out.println("\nThe first 6 bits aren't needed, so we'll shift the word:");        word = word >> 6;        System.out.println(toBinary(word, 16));         int mask = 0xFF;        System.out.println("\nOur mask looks like this: \n" + toBinary(mask, 16));         System.out.println("\nSo now, we'll AND the shifted word and the mask together...");        int messageId = word & mask;        System.out.println(toBinary(messageId, 8));         return messageId;    }     int getId(byte[] b) {        if (b.length != 2) throw new IllegalArgumentException("I need two bytes!");        int word = (b[0] << 8) | (b[1] & 0xFF);        return (word >> 6) & 0xFF;    }     String toBinary(int num, int bits) {        StringBuffer buf = new StringBuffer(Integer.toBinaryString(num));        int len = buf.length();        if (len > bits) buf.delete(0, len - bits);        while (len++ < bits) {            buf.insert(0, "0");        }        return buf.toString();    }}
 

Posts:24,036
Registered: 2/3/03
Re: My mask doesn't work for reading bits  
Jul 13, 2004 12:37 PM (reply 10 of 13)



 
Example output:
Here are our starting bytes (21, -33):
00010101 11011111

Now, we'll call the getMessageId() method...

First, we'll create the word.
Here is the first byte, shifted to the left:
0001010100000000

Here is the second byte, kept as it is:
0000000011011111

Now we will OR the two together...
...resulting in the word:
0001010111011111

The first 6 bits aren't needed, so we'll shift the word:
0000000001010111

Our mask looks like this:
0000000011111111

So now, we'll AND the shifted word and the mask together...
01010111

Our final message ID is:
87

And here's the short version: 87
 

Posts:11,200
Registered: 7/22/99
Re: My mask doesn't work for reading bits  
Jul 13, 2004 12:45 PM (reply 11 of 13)



 
It would be easier to use DataInputStream or RandomAccessFile which can read a 16 bit value for you directly.
DataInputStream in = new DataInputStream(new FileInputStream("file"));in.skip(2); // hopefully skip two bytes, should check return valueint word = in.readChar(); // read two bytesint messageId = (word >> 6) & 0xFF;in.close(); // close the file
 

Posts:24,036
Registered: 2/3/03
Re: My mask doesn't work for reading bits  
Jul 13, 2004 12:47 PM (reply 12 of 13)



 
It would be easier to use DataInputStream or
RandomAccessFile which can read a 16 bit value for you
directly.

Good point. :o)
 

Posts:343
Registered: 7/13/04
Re: My mask doesn't work for reading bits  
Jul 13, 2004 12:49 PM (reply 13 of 13)



 
thank you so much, problem solved.
 
This topic has 13 replies on 1 page.