• 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

    • No word on how much of an ewaste apocalypse this will cause.
    • The list of Mac devices rumored to get macOS 26 by Hamid Ganji Apple will announce macOS 26 or macOS Tahoe at its Monday Worldwide Developers Conference. As has been reported multiple times over the past weeks, all Apple operating systems will receive a UI overhaul, a touch of AI, and new names at this year's WWDC. The logic behind the "26" in the new macOS version is that Apple aims to align its naming schedule with its 2025-2026 release cycle. The same version number will also appear across iOS, iPadOS, watchOS, and tvOS. While skipping multiple software versions raises many questions, it might help maintain consistency in the Apple ecosystem. With just two days away from the WWDC kick-off, many Mac owners might wonder if the upcoming macOS 26 is compatible with their devices. Here's the rumored list of compatible Mac devices with the macOS 26: MacBook Air (M1 and later) MacBook Pro (2019 and later) iMac (2020 and later) Mac Mini (M1 and later) Mac Studio (all models) Mac Pro (2019 and later) This report comes from MacRumors, which cites a private account on X as the source. However, the interesting thing about this list is that, according to the leaker, Apple might end software support for the MacBook Pro 13-inch (2020 model, two Thunderbolt 3 ports). For now, we should take this claim with a pinch of salt. The 2020 MacBook Pro 13-inch launched with both Intel and Apple Silicon M1 processors. It also comes with two port configurations. Apple is expected to end support for more Intel-based Mac devices this year, and this specific MacBook Pro variant might also be on Apple's kill list. WWDC 2025 kicks off on June 9, and Apple will unveil the latest version of its operating systems with an overhauled UI and a slew of AI-related features. So far, we know what Apple Watch models might get watchOS 26. Apple will announce the compatibility list of various devices at Monday's event.
    • It's a separate question to the thread, but I have VLC and qBitorrent working on W11 without any issue. Download->install->job done.
    • Currently I am using Display Port connection to monitor.   If I change the setting you show above it does make text larger, but ALL text larger not just icon text on desktop. Also is doesn't change the text weight at all. That setting leaves it very thing test. I want bold, or semibold.
    • Patch My PC - Home Updater 5.2.3.0 by Razvan Serea Patch My PC Free is a reliable tool which can quickly check your PC for outdated software. The supported third-party programs include a large number of widely-used applications, including Adobe Reader, Mozilla Firefox, Java, 7-Zip, BleachBit, Google Chrome and many more. Patch My PC Home updater features: Updates over 500 common apps check including portable apps Ability to cache updates for use on multiple machines No bloatware during installations Applications install/update silently by default no install wizard needed Optionally, disable silent install to perform a manual custom install Easy to use user interface Change updated and outdated apps color for color blindness Option to automatically kill programs before updating it Create a baseline of applications if installing on new PC’s Quickly uninstall multiple programs Scan time is usually less than 1 second Set updates to happen on a schedule Skip updates for any application you don’t want to update Suppresses restarts when performing application updates Patch My PC - Home Updater 5.2.3.0 changelog: Startup Manager New tab to manage which apps launch at startup. This helps speed up your boot time and gives you control over what runs in the background. Generate Diagnostic ZIP You can now create a diagnostic ZIP file from the About page. This helps if you need to send logs on our support forum for Home Updater. Remove Portable Apps Right-click any portable app in the App Catalog or Uninstaller page to remove it directly. Applications Added FFmpeg (Full Shared) – Portable Fing G-Helper – Portable IntelliJ IDEA Community Edition K-Lite Basic Codec Pack K-Lite Full Codec Pack K-Lite Standard Codec Pack KeePass Password Safe v1 LibreOffice Help Pack MemTest86 – Portable Nexus Vortex Nvidia Profile Inspector – Portable Pale Moon – Portable ViVeTool – Portable WinCDEmu Windows PC Health Check Wise Video Converter Applications Removed Driver Easy Download: Patch My PC 5.2.3.0 | 54.8 MB (Freeware) Download: Patch My PC Portable | 31.0 MB (Portable) View: Patch My PC Free Homepage | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      abortretryfail earned a badge
      Week One Done
    • First Post
      Mr bot earned a badge
      First Post
    • First Post
      Bkl211 earned a badge
      First Post
    • One Year In
      Mido gaber earned a badge
      One Year In
    • One Year In
      Vladimir Migunov earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      490
    2. 2
      +FloatingFatMan
      258
    3. 3
      snowy owl
      249
    4. 4
      ATLien_0
      223
    5. 5
      +Edouard
      190
  • Tell a friend

    Love Neowin? Tell a friend!