• 0

[JAVA] Convert 1-2 bytes into a short


Question

Hi, I have a byte[] and I'm trying to get out 1-2 bytes depending on whether it's 8bit or 16bit and to convert this to a short value. I'm not really sure how to do this as obviously I can't just add the bytes together, and I need to make sure that I know whether it is positive/negative (and little/big endian).

Can anybody explain how to do this?

edit: I am presuming that you can get out the first byte and shift it left by 8, and then add it to the other byte. But then how do I know whether the two bytes are positive or negative.

This surely must be a rather standard problem, so I wonder if there is any sample code anywhere that I can look at?

Edited by lhnz
Link to comment
https://www.neowin.net/forum/topic/709892-java-convert-1-2-bytes-into-a-short/
Share on other sites

7 answers to this question

Recommended Posts

  • 0

Bit-shifting should be an easy way to do it, this is from my head and probably wrong, but:

short getValue(byte[] data) 
{	
	short value = data[1];
	value = (value << 8) | data[0];

	return value;
}

Also, please a Java-fellow correct me, but are all Java-based numbers signed and big-endian?

  • 0
  Antaris said:
Also, please a Java-fellow correct me, but are all Java-based numbers signed and big-endian?

Singed, yes, except for char which is 16 bit unsigned. I don't think the Java language definition has anything to say about the big/little endian-ness of the internal implementation (unless I missed it).

  • 0
  lhnz said:
Hi, I have a byte[] and I'm trying to get out 1-2 bytes depending on whether it's 8bit or 16bit and to convert this to a short value. I'm not really sure how to do this as obviously I can't just add the bytes together, and I need to make sure that I know whether it is positive/negative (and little/big endian).

Can anybody explain how to do this?

edit: I am presuming that you can get out the first byte and shift it left by 8, and then add it to the other byte. But then how do I know whether the two bytes are positive or negative.

This surely must be a rather standard problem, so I wonder if there is any sample code anywhere that I can look at?

how are you supposed to know if its 8 bit or 16 bit? is there a flag to tell u so?

and how do u know if its positive or negative? for example the binary representation of 255 is 11111111.. and if its signed it would be -127 isnt it? (something like that) so there is no way to tell if its negative or positive unless theres a flag that tells you so

  • 0

We need a bit more definition on this - how exactly do you need to "convert" two bytes to a short? If it's just concatenation then Anatris' solution is what you need (although maybe in the opposite order?), but if you want to interpret the byes as signed then you need to specify what result you would expect to see from pairs like, say 100,101 100,-101 -100,101 -100,-101

If you want to use the sign of both bytes (ie byte[0]*2^16 + byte[1]) then use byte[0]*2^16 + byte[1];

Edited by JamesCherrill
  • 0
  rejinderi said:
how are you supposed to know if its 8 bit or 16 bit? is there a flag to tell u so?

and how do u know if its positive or negative? for example the binary representation of 255 is 11111111.. and if its signed it would be -127 isnt it? (something like that) so there is no way to tell if its negative or positive unless theres a flag that tells you so

Flags that I am able to use for that are here: http://java.sun.com/j2se/1.4.2/docs/api/ja...udioFormat.html

  Antaris said:
short getValue(byte[] data)
{	
	short value = data[1];
	value = (value << 8) | data[0];

	return value;
}

This looks kind of like what I need. Is this for big-endian or little-endian data however? And what happens if the two bytes contain a negative or positive value?

I'll just give a little more information just in case others can help me further:

Okay, basically what I have is a byte array of the data inside a wav file. (Which I already know how to read in already etc...)

However in order to be able to easily calculate on this later on I want to convert the byte[] to a short[].

Obviously depending on the framesize (1 if 8bit, and 2 if 16bit) of the wav data each sample should either be 8 bytes or 16bytes long. So if the data is 16bit I will need to get 2 bytes from the byte[] and turn them into one short value. And if it is 8bit, I will need to get 1 byte and turn it into a short sample...

So what I'm asking in psuedo code is:

byte[] byteArray; // contains every single byte of the wav file in order.
short[] samples = new short[numberOfSamples];

short sample = 0;
if (frameSizeOfWavData = 1) { // Wav data is 8bits so get out one byte of sample and place it in the sample.
	sample = byteArray[0];
	samples[0] = sample;
} else { // Wav data is 16bits so get out 2 bytes of the byteArray
	sample = (byteArray[0] << 8) + byteArray[1]; // This is my guess of what I kind of need to do but I don't understand
	samples[0] = sample;
}

My issue is that I don't know how you can read a certain number of bytes into one short correctly.

Edited by lhnz
  • 0

I currently have:

	private short getSampleFromBytes(byte[] sampleBytes) {
		short sample = 0;
		for (int i = 0; i < sampleBytes.length; ) {
			int shift = 8 * (sampleBytes.length - (i + 1));
			sample |= (sampleBytes[i]) << shift;
		}
		return sample;
	}

Does that look right?

  • 0
  lhnz said:
I currently have:

	private short getSampleFromBytes(byte[] sampleBytes) {
		short sample = 0;
		for (int i = 0; i < sampleBytes.length; ) {
			int shift = 8 * (sampleBytes.length - (i + 1));
			sample |= (sampleBytes[i]) << shift;
		}
		return sample;
	}

Does that look right?

what does the sample bytes stand for?.. you dont need to convert everything into a short array?.. why are u ORing them this way.. i dont understand i thought u were supposed to like take the sample bytes and then convert them all into a short array depending on the framesize?

		private short GetShort(byte[] b)
		{
			short retVal;

			if (b.Length == 1)
				retVal = b[0];
			else 
				retVal = (short)(b[1] << 8 | b[0]); //for big endian
				// retVal = (short)(b[0] << 8 | b[1]);//for little endian

			return retVal;
		}

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Nvidia App gets light theme, bug fixes, and support for more games by Taras Buria Nvidia has released a new update for the Nvidia App on Windows. Version 11.0.4 is now available with a few changes, such as automatic theme switching with light mode support, Windows Narrator support, fixed bugs, and optimal settings for 12 new games. With today's update, Nvidia App now supports light mode. You can switch between modes in settings or let the app follow the system settings (Windows still does not support automatic theme switching). To change the mode, go to Settings > Features > Theme. In addition, Nvidia App now supports Windows Narrator. The system's native screen reader can now properly read aloud on-screen content to improve accessibility for those relying on assistive technologies. Next, the list of games that Nvidia App can tune for optimal performance has been extended with 12 new titles: Assassin's Creed: Shadows Clair Obscur: Expedition 33 Deadlock ELDEN RING NIGHTREIGN Grand Theft Auto V Enhanced Half-Life 2 with RTX Indiana Jones And The Great Circle inZOI Monster Hunter Wilds Split Fiction The Last of Us Part II Remastered The Elder Scrolls IV: Oblivion Remastered Finally, Nvidia App 11.0.4 fixes the following bugs: Fixed an issue where DLSS-FG defaults to 2x irrespective of in-game setting when DLSS override model is set to "Latest” and Frame generation is set to “Use the 3D application setting". Fixed an issue where the driver download could not be completed. Fixed an issue where the recording bitrate setting was not saved. Fixed an issue where HDR video colors were not encoded properly for HEVC and AV1 playback. Fixed a bug where the in-game overlay was not accessible on the GeForce RTX 5070. Fixed an issue where a PC reboot would reset microphone boost to an incorrect value. Fixed an issue where Highlights summary window could not be disabled. Various stability fixes. You can download the Nvidia App from the official website. Full release notes are available here.
    • Ai is terrible at showing us existing knowledge. Hallucinating s**t is not exactly "discovering".
    • You know, this is mostly Edge related? It also affects just EU people.
  • Recent Achievements

    • Conversation Starter
      lilyandrew11 earned a badge
      Conversation Starter
    • Contributor
      Ed B went up a rank
      Contributor
    • One Month Later
      moporcho earned a badge
      One Month Later
    • One Month Later
      Parotel earned a badge
      One Month Later
    • Reacting Well
      Cryptecks earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      188
    2. 2
      snowy owl
      135
    3. 3
      ATLien_0
      131
    4. 4
      Xenon
      120
    5. 5
      +FloatingFatMan
      100
  • Tell a friend

    Love Neowin? Tell a friend!