Solved

Can you convert two bytes to one double or int

Posted on 2003-12-03
16
673 Views
Last Modified: 2011-10-03
I did a application to extract data from .wav file, and got a byte array, for this program each frame(equals to one sample) includes 2 bytes, I want to convert those two bytes to one int or double for further analysis. please help ...
here is the example made by my friend bsampieri,,
// bsampieri 's code

intArr = new int[numBytes/2];
for (int i=0; i<numBytes/2; i++) {
byteA = (int)tempBuffer1;
byteB = (int)tempBuffer1[i+1];
if(byteA < 0) byteA += 0x100;
if(byteB < 0) byteB += 0x100;

if(audioInputStream.getFormat().isBigEndian())
intArr = ((int)byteA) + (((int)byteB) << 8); // big endian
else
intArr = ((int)byteB) + (((int)byteA) << 8); // little endian

} //end for

for(int j=0;j<numBytes/2;j++)
System.out.println(intArr[j]);

// bsampieri 's code


if you have more suggestion, please tell me , thanks bsampieri and
your guys
0
Comment
Question by:royoz2003
16 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 9865882
an int is arranged like this:
[===byte===][===byte===][===byte===][===byte===]

And a double, like this:
[===byte===][===byte===][===byte===][===byte===][===byte===][===byte===][===byte===][===byte===]

How do you want the bytes to be placed into the int or double for further analysis?

What sort of analysis do you want to do?
0
 

Author Comment

by:royoz2003
ID: 9865994
Thanks TimYates for your reply:
I want to use those double data to do fourier transform , and plot the waveform, maybe more signal processing,   I am new to java , and also not familiar with file formats, So confusing about digital audio processing with java
can you say about that ?   thank TimYates
0
 

Author Comment

by:royoz2003
ID: 9866023
this is detail of program, after I got the byte array , I don't know how to use them to do signal processing, in this program, one frame includes two bytes , it means one sample has two bytes, this is the reason why I want to convert two bytes to one double(each sample), maybe it's incorrect, I don't know, so confusing ,,,,,help , help .....can you give me some suggestions about that
import java.util.*;
import java.io.*;
import javax.sound.sampled.*;
import java.lang.*;
import java.lang.Long.*;
import java.math.*;

public class waveform1 {
 
  File soundFile =
                   new File("test.wav");

  byte[] tempBuffer1;
  double[] doubArr;
  int numBytes;
  short[] shortArr;
 
 public static void main(String args[])
  {
    new waveform1();
  }//end main    
 
 
  public waveform1(){//constructor
   
   AudioFormat audioFormat;
   AudioInputStream audioInputStream;    
   int bytesPerFrame;
   int bitesPerFrame;
   int sampleSizeInBits1;
   long FrameLength;
   int FrameLength1;
   SourceDataLine sourceDataLine;
 
   int totalFramesRead=0;  
 
   try{
     
      audioInputStream = AudioSystem.
                  getAudioInputStream(soundFile);
           
      bytesPerFrame=audioInputStream.getFormat().getFrameSize();
      sampleSizeInBits1=audioInputStream.getFormat().getSampleSizeInBits();
      FrameLength=audioInputStream.getFrameLength();
      FrameLength1=(int)FrameLength;
      numBytes=FrameLength1*bytesPerFrame;
      tempBuffer1 = new byte[numBytes];
      bitesPerFrame=bytesPerFrame*8;
      System.out.println(FrameLength);
      System.out.println(bytesPerFrame);
      System.out.println(sampleSizeInBits1); //16 bits
    try{
      int numBytesRead=0;
      int numFramesRead=0;
 
     while((numBytesRead = audioInputStream.
        read(tempBuffer1)) != -1){
        numFramesRead=numBytesRead/bytesPerFrame;
        totalFramesRead+=numFramesRead;
   
   
      doubArr = new double[numBytes/2];
                for (int i=0; i<numBytes/2; i++) {
                       
                   doubArr[i] =
                           
                           Math.pow(tempBuffer1[i*bytesPerFrame+0]+bitesPerFrame, 0.0)+
                           Math.pow(tempBuffer1[i*bytesPerFrame+1]+bitesPerFrame, -1.0);
                           }
           
           for(int j=0;j<numBytes/2;j++)
           System.out.println(doubArr[j]);
     
      /*
      //code from tschodt
     
      shortArr = new short[numBytes/2];
      for(int i=0;i<numBytes/2;i++)
      {
      shortArr[i] = ( tempBuffer1[i*bytesPerFrame+1] << 8 ) | tempBuffer1[i*bytesPerFrame+0];  
       }
        for(int j=0;j<numBytes/2;j++)
        System.out.println(shortArr[j]);
       //code from tschodt */
                 
      }//end while
      }catch (Exception ex) {
     }//end catch
     
       
    } catch(Exception e){
    } //end of catch
       
     
    } //constructor end
   
    }//class end
   
   
       
0
 
LVL 35

Accepted Solution

by:
TimYates earned 20 total points
ID: 9866061
> it means one sample has two bytes

Ok, so each sample is 2 bytes long...

assuming that means a sample can be between

-32768 <= sample <= 32767

And you have an array of bytes stored in "byteArr" (which is a load of byte-pairs)

you end up with:

doubleArr = new double[ numBytes / 2 ] ;
for( int i = 0 ; i < numBytes / 2 ; i++ )
{
    int byteA = (int)( byteArr[ ( i * 2 ) & 0xFF );
    int byteB = (int)( byteArr[ ( i * 2 ) + 1 ] & 0xFF ) ;

    if( audioInputStream.getFormat().isBigEndian() )
        doubleArr[ i ] = ( byteA ) | ( byteB << 8 ) ; // big endian
    else
        doubleArr[ i ] = ( byteB ) | ( byteA << 8 ) ; // little endian
}
0
 
LVL 4

Expert Comment

by:vk33
ID: 9866062
Why not using short? It is two-bytes long...
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9866069
Hmmm...hope I helped...  I am not sure how to do signal processing....it's just something I never looked into very deeply...

This looks quite interesting (though maybe not useful):

http://www.falstad.com/fourier/j2/Fourier.java
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9866085
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 9866144
     byte []a=new byte[2];
            a[0]=10;
            a[1]=0;
            BigInteger bi=new BigInteger(""+a[0]);
            String str=bi.toString(2);
            int len=str.length();
            for(int i=1;i<=8-len;i++)
            {
                  str="0"+str;
            }

             bi=new BigInteger(""+a[1]);
            String str1=bi.toString(2);
            len=str1.length();
            for(int i=1;i<=8-len;i++)
            {
                  str1="0"+str1;
            }

            str=str+str1;  //binary value of 2 bytes as a string. You need to covert it into integer again


Is this what you are expecting?



0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Author Comment

by:royoz2003
ID: 9866211
Thanks TimYates and vk33
thank very much indeed for your reply:
TimYates, I used your code in my program, fortunately, I got the double array, something like that:
46335.0
46567.0
63423.0
61266.0
11264.0
and a lot of
17432.0
17645.0
17634.0
17***.0
a lot of 17***.0 in the end of double array
........


that's wonderful,  but I have another question, there is no negative value,,, if  I have to plot them, maybe  I will fall into trouble,
can u say something about it , if you have time

                                      thanks ,,,,,,,,,,,
                                         Roy
0
 

Author Comment

by:royoz2003
ID: 9866245
thanks again , TimYates
thank you very much indeed, thanks
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9866334
> there is no negative value,,, if  I have to plot them, maybe  I will fall into trouble,

Hmmm...yeah...maybe...it depends how your bytes are representing the data...

You could do:

doubleArr = new double[ numBytes / 2 ] ;
for( int i = 0 ; i < numBytes / 2 ; i++ )
{
    byte a = byteArr[ ( i * 2 ) ] ;
    byte b = byteArr[ ( i * 2 ) + 1 ] ;
    boolean negative = a < 0 || b < 0 ;
    int byteA = (int)( a & 0xFF );
    int byteB = (int)( b & 0xFF ) ;

    if( audioInputStream.getFormat().isBigEndian() )
        doubleArr[ i ] = ( byteA ) | ( byteB << 8 ) ; // big endian
    else
        doubleArr[ i ] = ( byteB ) | ( byteA << 8 ) ; // little endian
    if( negative )
        doubleArr[ i ] *= -1 ;
}

But that may make no sense....as I say, it really depends on what your byte array is representing, and how it is representing it...

play around with how the bytes are put together, bsampieri's code that you posted at the start deals with negative values differently to mine...  maybe his is the correct way (0x100 instead of & 0xFF)

Hope you get this sorted :-)

Good luck!

Tim
0
 

Author Comment

by:royoz2003
ID: 9866474
Hi Tim:
I run your program, fortunately, it makes sense,  fantastic
you are genius!!!

see the result
(segment)
-57082.0
12288.0
14339.0
28420.0
27651.0
-32535.0
-26353.0
-57543.0
-40453.0
9216.0
.......

just in the end of array
all the value are 17***.0
hehe, maybe I have to minus 17000.0 from each data in order to get a wonderful waveform, hehe
Thanks god
Thanks Tim,  
now I can eat some biscuit,  so hungry
0
 

Author Comment

by:royoz2003
ID: 9866559
Tim. see u tomorrow, good luck and have a nice day
I have to leave , because here in Melbourne, is already 1:00 in the night , all the entrance in my universtiy will be closed, ,

                          see u ,  thanks
                              ROy
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9866570
> maybe I have to minus 17000.0 from each data in order to get a wonderful waveform

Hee hee, yeah, maybe :-)

Or the code that makes the doubles might need a *bit* of messing around with ;-)

Check it against bsampieri's code (the one that does integers), and see if his gives similar results :-)

Good luck!

And happy eating ;-)

Tim
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9866577
>  Tim. see u tomorrow, good luck and have a nice day

Thanks :-)

> I have to leave , because here in Melbourne, is already 1:00 in the night , all the entrance in my universtiy will be closed, ,

Eeeek!  Straight to bed for you!!!

2pm here...  roll on 5, so I can go home ;-)

hehehe

Tim
0
 

Author Comment

by:royoz2003
ID: 9872041
Hi I check the program which doese short integers : found the result looks like that
123
45
-93
24
55
54
-45
23
at the end of short array
all the data are 6*,such 68, 67, 69, some 70
same situation as your code
do I need to minus 70 from each data
if I do it , can the new result reflects  data in .wav file precisely and accurately
thanks

Roy
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
java set up 1 47
eclipse compiler vs Installed JREs option 3 40
JList custom Cell Renderer refresh 15 43
eclipse java  build path 6 21
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now