• 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

    • Wish you could set the WiFi country without setting an SSID. This would stop the warning on every boot.
    • Huawei's Mate XT successor launches this year with a performance and camera boost by Hamid Ganji Last year, Huawei reimagined our perception of folding smartphones by launching the world's first tri-folding device, Mate XT. Contrary to regular folding smartphones like the Samsung Galaxy Z Fold 6, the Huawei Mate XT utilizes a dual-hinge mechanism that allows the device to fold into a "Z" shape. The success of the Mate XT has allegedly prompted Huawei to release a sequel this year. Chinese tipster Digital Chat Station on Weibo says Huawei will release a successor in the second half of 2025. While the folding and screen solution remain unchanged, the tipster claims the second-generation Mate XT gets a faster processor and upgraded camera setup. Digital Chat Station says Huawei will also improve the device's accessories. Last year's Mate XT included an Aramid Fiber Case with an integrated rotating stand in the box as official accessories. Though the tipster doesn't mention quality improvements, Huawei could reinforce the phone's folding endurance. As for the release date, the first-generation Mate XT was released in September 2024, and the Mate XT 2 might also be released at the same time. Interestingly, Huawei announced its Mate XT, the world's first tri-folding device, on September 10 last year, just one day after Apple announced its iPhone 16 series. If Huawei wants to tease Apple again, we can expect the Mate XT 2 to drop simultaneously with the iPhone 17 series. While these devices are not in the same category, Huawei's rivalry with Apple is common knowledge. Tri-folding smartphones provide bigger screens at a more compact size compared to tablets. For example, the Huawei Mate XT has a screen size of 10.2 inches when it's fully open and 7.9 inches when folded once. Also, when you fold it twice, you get a 6.4-inch screen like regular smartphones. Huawei is now the biggest contender in the tri-folding segment, but Samsung may also join the race with a tri-fold version of its Galaxy Fold devices.
    • You can now measure internet speed and download videos using PowerToys Run by Taras Buria PowerToys Run is among my favorite modules, which I use daily (some of them should be integrated into Windows 11). This powerful utility is great for finding stuff, launching apps, navigating the web, and a lot more. Third-party modules help expand PowerToys Run's functionality and add additional capabilities like controlling Spotify, asking ChatGPT, and more. Now, there are three new modules you may find useful: speed test, video downloader, and vocabulary. The SpeedTest module uses Ookla Speedtest CLI for local execution without third-party tracking or ads. It has a modern, theme-aware user interface, and runs with a single command: just open Run and type spt to measure your internet connection speed. The result will show up in a new window with the ability to copy the result URL. The module also supports x64 and ARM systems. The VideoDownloader plugin lets you download videos from YouTube and other websites. You can specify the video quality and format (audio-only, for example) and select where to save the video. To make it work, open PowerToys Run, type dl and add a video URL. Finally, the Definition plugin from the same developer works as a powerful vocabulary that offers word definitions, word pronunciations, phonetics and synonyms, usage examples, and more. Note that these modules are not available in PowerToys out of the box. You need to download them from GitHub and install them manually. Here is how to do that: Download SpeedTest, VideoDownloader, or Definition plugins from their GitHub repositories. Extract downloaded plugins into %LOCALAPPDATA%\Microsoft\PowerToys\PowerToys Run\Plugins\ Open PowerToys Run (Alt + Space is the default shortcut) and launch plugins using their corresponding shortcuts (spt, dl, or def, all three can be customized in settings). You can also configure plugins in PowerToys Run settings. You can find more third-party modules for PowerToys Run on GitHub.
    • Showing people how to self host their own media is harmful, according to YouTube by David Uzondu YouTube has taken down a video from tech creator Jeff Geerling that demonstrated how to use LibreELEC, a lightweight operating system for turning devices into media centers, on a Raspberry Pi 5 for 4K video playback. The video, titled "I replaced my Apple TV—with a Raspberry Pi", originally published in May 2024, was removed in June 2025 under YouTube's "Harmful or dangerous content" policy. According to the violation notice, YouTube claimed the video showed "how to get unauthorized or free access to audio or audiovisual content, software, subscription services, or games that usually require payment." Image via Jeff Geerling Geerling strongly refuted YouTube's claims. He stated clearly, "I purposefully avoid demonstrating any of the tools that are popularly used to circumvent purchasing movie, TV, and other media content." He also emphasized that his own Network Attached Storage, or NAS, contains only legally acquired content. This isn't Geerling's first run-in with YouTube over self-hosted media tools. Last October, his tutorial titled "Better than Disney+: Jellyfin on my NAS" was hit with a similar strike for showing how to set up Jellyfin, an open source media server for organizing and streaming personal media. That strike was quickly overturned after an appeal. But this time, YouTube rejected his appeal, even though the LibreELEC video had been live for over a year, had racked up over half a million views, and contained no promotion of anything illegal. This whole thing feels a lot like what happened with youtube-dl. It's a simple command-line tool for downloading videos, used by tons of people for perfectly legal reasons like saving public domain content or backing up their own uploads. But that didn't stop the RIAA from hitting it with a DMCA takedown on GitHub, calling it a piracy tool. The community pushed back hard, and eventually it was brought back, thanks in part to support from groups like the Electronic Frontier Foundation who pointed out that not everything that can be misused is automatically bad. Side note, the youtube-dl project appears to be unmaintained (the last release was in 2021), if you're looking for an alternative, consider its very popular fork, yt-dlp. After the appeal was rejected, YouTube required Geerling to complete "policy training" to avoid a more serious, permanent strike on his channel. He eventually gave in and took the training. Anyways, if you're interested, he has uploaded the removed LibreELEC video to Internet Archive for anyone to watch.
    • Thanks to Herr Musk being a total poison pill, they can't even give those pieces of scrap away.  They can't even ship them to the UK/EU because they're completely illegal over here.  
  • Recent Achievements

    • Week One Done
      luxoxfurniture earned a badge
      Week One Done
    • First Post
      Uranus_enjoyer earned a badge
      First Post
    • Week One Done
      Uranus_enjoyer earned a badge
      Week One Done
    • Week One Done
      jfam earned a badge
      Week One Done
    • First Post
      survivor303 earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      436
    2. 2
      +FloatingFatMan
      237
    3. 3
      snowy owl
      219
    4. 4
      ATLien_0
      210
    5. 5
      Xenon
      152
  • Tell a friend

    Love Neowin? Tell a friend!