We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,304 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

How to output byte value (8 bits) in java?

Hi there,
My question is how could I output byte value (meaning zeros and ones) to screen.
I just want to try some shifts and see how it works.

2
Contributors
14
Replies
3 Days
Discussion Span
1 Year Ago
Last Updated
18
Views
Question
Answered
IcantC
Newbie Poster
15 posts since May 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Look at the Integer class. It has methods to convert int values to different Strings for displaying.

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

Look at the Integer class. It has methods to convert int values to different Strings for displaying.

Thank you for your effort.
What I have is a byte array. I have tried converting byte to int and then outputting it's (int's) binary representation as String like you said:

System.out.println(Integer.toBinaryString( (int) arrayOfBytes[1]));

But it seems the way around and I'm not sure whether the result is what I need.
I also tried to output all byte array as a hex array, like this (this gives me ASCII codes of bytes in a hex format):

System.out.println(getHexString(arrayOfBytes));

These two ways give me different results and I am not sure which one is the REAL ONE :)
I know there are plenty ways of how one can 'understand' a byte but
what I need is raw binary data as it is in a file.
My task is to do complex binary operations (count frequencies of n bit sequences and so on) so i need to know the exact content.

IcantC
Newbie Poster
15 posts since May 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

it seems the way around and I'm not sure whether the result is what I need.

Can you show what the code outputs and explain what is wrong with it and give an example of what you want to print?

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

Can you show what the code outputs and explain what is wrong with it and give an example of what you want to print?

Ok, my file's content is:
2
As I try to output like this S.o.p(Integer.toBinaryString( (int) arrayOfBytes[1])) , I get:
1010
And when I am doing this S.o.p(getHexString(arrayOfBytes)) , I get
320a

Now obviously when printing the second time what I get is ASCII code of the symbol 2 and new line symbol. And what do I get the first time is what I don't know. I would expect it to be 0010. If value 1010 is correct I am fine with it I just want to know if It's the correct value and why.

IcantC
Newbie Poster
15 posts since May 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Without the full data, I can not explain what you are seeing.

S.o.p(Integer.toBinaryString( (int) arrayOfBytes[1]))

What does arrayOfBytes[1] contain? It looks like it has an int value of 10

S.o.p(getHexString(arrayOfBytes))

What is arrayOfBytes here? What does the getHexString() method do? What does it take for an argument?

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

Without the full data, I can not explain what you are seeing.

S.o.p(Integer.toBinaryString( (int) arrayOfBytes[1]))

What does arrayOfBytes[1] contain? It looks like it has an int value of 10

S.o.p(getHexString(arrayOfBytes))

What is arrayOfBytes here? What does the getHexString() method do? What does it take for an argument?

I will give you full code:

// Returns the contents of the file in a byte array.

public class BytesExample
{

public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream fileInputStream = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
           && (numRead=fileInputStream.read(bytes, offset, bytes.length-offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file "+file.getName());
    }

    // Close the input stream and return bytes
    fileInputStream.close();
    return bytes;
    }

    public static String getHexString(byte[] b) throws Exception 
    {
        String result = "";
        for (int i=0; i < b.length; i++) 
        {
                result +=
                Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
        }
    return result;
    }

    public static void main(String args[])
    {
        try
        {
            File file = new File("output.txt");
            byte[] arrayOfBytes = getBytesFromFile(file);
            
            System.out.println(Integer.toBinaryString( (int) arrayOfBytes[1]));
            System.out.println(getHexString(arrayOfBytes));
        }
        catch (IOException e)
        {
            JOptionPane.showMessageDialog(null,
                     e.getMessage() +
                           "\nError while dealing with files" ,
                               "\n... ",
                                   JOptionPane.PLAIN_MESSAGE);
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null,
                     e.getMessage() +
                           "\nKError while converting bytes to String" ,
                               "\n... ",
                                   JOptionPane.PLAIN_MESSAGE);
        }

    }                 
    
}
IcantC
Newbie Poster
15 posts since May 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Can you answer my questions? Or change your code to have all the data be in the program. Remove reading data from a file. Hardcode the data in the program so there is no questions about what is in the file.

What does arrayOfBytes[1] contain? It looks like it has an int value of 10

What is arrayOfBytes here? use Arrays.toString() to format the content of the array and print it

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

Your code is missing the import statements.
When I execute it with a '2' as input I get:
java.lang.ArrayIndexOutOfBoundsException: 1

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

Can you answer my questions? Or change your code to have all the data be in the program. Remove reading data from a file. Hardcode the data in the program so there is no questions about what is in the file.

What does arrayOfBytes[1] contain? It looks like it has an int value of 10

What is arrayOfBytes here? use Arrays.toString() to format the content of the array and print it

ArrayOfBytes contains bytes that were read from the file. ArrayOfBytes[1] should contain the value of the first byte that was in a file. Method getHexString takes byte array as an argument and makes hexadecimal String representation of it. Even thou I don't see point in that, I have changed my program so that it wouldn't use file as an input. Now my main looks like this

public static void main(String args[])
    {
        try
        {
            byte[] bytes = new byte[20];
            String s = "2";
            bytes[0] = Byte.decode(s);
            System.out.println(Integer.toBinaryString( (int) bytes[1]));
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null,
                     e.getMessage() +
                           "\n Error encountered" ,
                               "\n... ",
                                   JOptionPane.PLAIN_MESSAGE);
        }
    }
    
}

After compiling and running this I get output:
0
Look, all I need to know is: what is in the file (in ones and zeros). Isn't there a quick way to achieve this?

IcantC
Newbie Poster
15 posts since May 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

What is the problem with your program? Does it read the bytes from the file correctly?
Get a hexeditor look at the bytes in the file and compare them to what your program reads.

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

Look at the indexes you are using on line 7 and line 8

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

Look at the indexes you are using on line 7 and line 8

Yah, I've just noticed. I used bytes[1] expecting to get first element. My bad.
So when I save one symbol to file, the file's content in binary format is just ASCII codes of that symbol and line feed symbol. Is that true?

IcantC
Newbie Poster
15 posts since May 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

So when I save one symbol to file, the file's content in binary format is just ASCII codes of that symbol and line feed symbol. Is that true?

Probably.
You should get a hex editor and look at the contents of a text file to see the values of the bytes in the file in hex.

NormR1
Posting Sage
Team Colleague
7,742 posts since Jun 2010
Reputation Points: 1,158
Solved Threads: 793
Skill Endorsements: 16

Probably.
You should get a hex editor and look at the contents of a text file to see the values of the bytes in the file in hex.

Ok, thanks. I'll move on :)

IcantC
Newbie Poster
15 posts since May 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 1 Year Ago by NormR1

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.1038 seconds using 2.72MB