Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Can you convert two bytes to one double or int

Posted on 2003-12-03
16
Medium Priority
?
725 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 35

Accepted Solution

by:
TimYates earned 80 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
 

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

New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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 third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

704 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