If I have the following:
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
I know that the size of each element would be one byte. But what I don't seem to understand is how would the integer 87 be stored in one byte? Or, how does the byte[] store data?
EDIT: I see that you can store -128 to 127 in a byte here in java. So, does that mean there is no way to store anything greater than or lesser than those numbers in a byte[]? If so, doesn't that limit the use of this? Or am not understanding the exact places to use a byte[].
A byte is 8 bits. 2^8 is 256, meaning that 8 bits can store 256 distinct values. In Java, those values are the numbers in the range -128 to 127, so 87 is a valid byte, as it is in that range.
Similarly, try doing something like byte x = 200, and you will see that you get an error, as 200 is not a valid byte.
A byte is just an 8-bit integer value. Which means it can hold any value from -2^7 to 2^7-1, which includes all of the number in {87, 79, 87, 46, 46, 46}.
An integer in java, is just a 4-byte integer, allowing it to hold -2^31 to 2^31 - 1
A Java byte is a primitive with a minimum value of -128 and a maximum value of 127 (inclusive). 87 is within the allowed range. The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters.
A byte[] is an Object which stores a number of these primitives.
I think the short answer is that byte[] stores bytes. The number 87 in your array above it a byte, not an int. If you were to change it to 700 (or anything higher than 127) you'd get a compile error. Try it.
You can use byte to store values of 8 bit in it which have a (signed) range from from -128 to 127.
With byte[] you can do some special operations like building Strings from a given bytestream and decode them with a desired Charset, and some functions will give you byte[] as their return value.
I don't know enough about the internals of the JVM but it might save memory though.
this is because, the computer stores values in a circular progression. not a linear progression like we learn in mathematics. it is because the memory is not infinite. it is finite. so every data type is storing values as a circular progression. to learn more go to this link and read the article.
https://medium.com/#hmsathyajith/numbering-system-edge-cases-of-java-237377553444
Related
I am reading a book about Java programming and in the first chapter it says: "The number 149 is stored in the byte at address 16" - is storing three characters, the 1, the 4, and the 9 in one byte possible?
No, the size of a character in java is 2 bytes. Thus obviously 6 bytes cannot fit into 1.
I think the book was trying to ask whether the number 149 could fit into a byte, in which yes and no, an unsigned byte can hold a value of 255 at max while a two's complement (signed) byte can only hold a value of 126.
Info about primitive data type
Storing the number 149 and characters '1', '4', and '9' separately are completely different. Storing the character '1' is actually storing its ASCII value 49, and the ASCII value 52, and 57 represent '4' and '9 respectively. The size of each character in Java is 2 bytes. So therefore 3 characters with a total size of 6 cannot fit into a single byte.
The byte data type is only 8 bits, and therefore it can store numbers from -128 to +127. That means the maximum value for a byte (Byte.Max_VALUE) is 127, and since 149 is bigger than 127, therefore it cannot fit into a byte, and you have to at least use a short to store 149. A short is 2 bytes in java.
I highly encourage you to read this Java documentation on data types. It's very short, but pretty useful to understand everything about data types.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
In General, A byte is 8 bits and can store a number range from 0 to 255. Bytes are often used in RAW data processing and is how data is stored in memory. When storing characters or a "String", you are storing a sequence of bytes that represent a sequence of characters.
the number 149 in binary Byte form is 10010101
Decimal to Binary Converter
But storing characters are different than storing numbers. To address you question, storing the characters "1", "4", and "9" in a single byte is not possible, but storing the number 149 is.
Also, the number of bytes that a given character/string uses are highly dependant on which encoding you are using.
Java String see .getBytes(Charset charset)
All this being said, a byte in Java is signed. Its range goes from -128 to +127 inclusive. A byte can store 256 unique values. You can think of them as numbers, individual flags, whatever you want. I have no context to the OP's original problem, but if they are using a Java primitive byte, it cannot by default hold the number 149. IF you are talking about a sequence of 8 bits, it can.
Java Primitive Datatypes
I have this code in C#
byte[] t = {6, 250, 215}.
But in Java is
byte[] t = {6, -6, -41}.
How to solve this problem?
How to solve this problem
the 1st is read about how java represents data types..:
byte: The byte data type is an 8-bit signed two's complement integer.
It has a minimum value of -128 and a maximum value of 127 (inclusive).
The byte data type can be useful for saving memory in large arrays,
where the memory savings actually matters. They can also be used in
place of int where their limits help to clarify your code; the fact
that a variable's range is limited can serve as a form of
documentation.
as #bradimus statements, java's byte is an 8-bits 2 complement signed int
but in C# you will never see a negative byte value
Hint:
if you consider to make a conversion...
-6 in java can be 256+(-6) = 250 in C#
and carefully consider the max and min in a java-byte if you need to convert from C# to java....
I am trying to take hex values and move them into a byte array. When I do this they are not converted how I need them to be. Most of them are converted to negative numbers. For example, after the execution of the C# code "baCommandPDI[0] = 0xD1;", the value of baCommandPDI[0] is "209". This is what I need. No matter what I try in Java, the value is "-47". I need it to be "209" in the byte array, because this byte array is sent out over TCP/IP to some external hardware. The external hardware cannot interpret -47 as 209. It must be 209. I have tried the following code:
int intTemp = 0xD1; After this line is executed the value of intTemp is 209, great!
int intHexValue = 0xD1 & 0xFF; After this line is executed the value of intHexValue is still 209, I don't understand how, but it ia what it is.
baCommand[0] = (byte) intHexValue; After this line is executed the value of baCommand[0] is -47, bad. This is not what I want. Everytime it converts the value to a byte it makes it signed.
Is there any other way I can do this? Can I use 11010001 and some how assign that value to a byte without making it negative?
In Java, bytes are always signed. But like an unsigned byte in another language, 8 bits are still used. The byte representations for 209 (unsigned) and -47 are the same.
1101 0001
The only difference is how Java interprets the most significant bit -- -128 vs. 128 in an unsigned type. The difference is 256, which is the difference between 209 and -47. You can send the value as is, because the bit values are the same, only the interpretations of this bit pattern are different.
If you would like to convert the value -47 to 209 to convince yourself in Java, you can promote the type to a longer primitive type and mask out the last 8 bits. This line will do this is one line, so you can debug and see that the bits are the same and that the unsigned version is equivalent.
int test = baCommandPDI[0] & 0xFF;
Printing/debugging test will let you see the value 209.
Java does not have a concept of unsigned bytes.
To get 209 from 0xD1, try:
0xD1 & 0xFF;
I was trying to store byte value in a variable and trying to perform some logic based upon this calculation.
byte mByteValue = -129; // Holding byte value
Problem is I am always getting value 127, due to which my logic fails everytime.
Any specific reason behind this, why its behaving strange in my case?
A byte in java is a signed 8-bit value. 8 bits gives you 256 possible values, but since a byte is signed and can represent positive and negative values, those 256 values must be roughly split in half across the possible positive and negative values. So you can't store negative values past -128; in particular don't expect to be able to store -256.
What you're actually observing when your byte has the value 127 is known as overflow (see this wiki article)
If you need to manipulate values outside this range, as in your example code, or e.g. an unsigned byte, at some point you'll need to make use of a wider integer type, like short.
The standard libraries provide these limits as Byte.MIN_VALUE and Byte.MAX_VALUE (docs here and here).
The range of byte is from -128 to 127. You can not store any value beyond these range.
This is because byte is 8 bits. So the maximum positive number stored at byte is -
2^7 -1 = 127. // since the first bit is sing bit; 0 for positive
And minimum negative number stored at byte is-
2^7 = -128 //since the first bit is sign bit; 1 for negative.
And if you use unsigned byte the it would be 255.
To correctly convert a byte to an int use mByteValue & 0xFF. You can read more about the Two's complement here: https://en.wikipedia.org/wiki/Two%27s_complement.
I read this line in the Java tutorial:
byte: The byte data type is an 8-bit signed two's complement integer. It has
a minimum value of -128 and a maximum value of 127 (inclusive). The
byte data type can be useful for saving memory in large arrays, where
the memory savings actually matters. They can also be used in place of
int where their limits help to clarify your code; the fact that a
variable's range is limited can serve as a form of documentation.
I don't clearly understand the bold line. Can somebody explain it for me?
Byte has a (signed) range from -128 to 127, where as int has a (also signed) range of −2,147,483,648 to 2,147,483,647.
What it means is that since the values you're going to use will always be between that range, by using the byte type you're telling anyone reading your code this value will be at most between -128 to 127 always without having to document about it.
Still, proper documentation is always key and you should only use it in the case specified for readability purposes, not as a replacement for documentation.
If you're using a variable which maximum value is 127 you can use byte instead of int so others know without reading any if conditions after, which may check the boundaries, that this variable can only have a value between -128 and 127.
So it's kind of self-documenting code - as mentioned in the text you're citing.
Personally, I do not recommend this kind of "documentation" - only because a variable can only hold a maximum value of 127 doesn't reveal it's really purpose.
Integers in Java are stored in 32 bits; bytes are stored in 8 bits.
Let's say you have an array with one million entries. Yikes! That's huge!
int[] foo = new int[1000000];
Now, for each of these integers in foo, you use 32 bits or 4 bytes of memory. In total, that's 4 million bytes, or 4MB.
Remember that an integer in Java is a whole number between -2,147,483,648 and 2,147,483,647 inclusively. What if your array foo only needs to contain whole numbers between, say, 1 and 100? That's a whole lot of numbers you aren't using, by declaring foo as an int array.
This is when byte becomes helpful. Bytes store whole numbers between -128 and 127 inclusively, which is perfect for what you need! But why choose bytes? Because they use one-fourth of the space of integers. Now your array is wasting less memory:
byte[] foo = new byte[1000000];
Now each entry in foo takes up 8 bits or 1 byte of memory, so in total, foo takes up only 1 million bytes or 1MB of memory.
That's a huge improvement over using int[] - you just saved 3MB of memory.
Clearly, you wouldn't want to use this for arrays that hold numbers that would exceed 127, so another way of reading the bold line you mentioned is, Since bytes are limited in range, this lets developers know that the variable is strictly limited to these bounds. There is no reason for a developer to assume that a number stored as a byte would ever exceed 127 or be less than -128. Using appropriate data types saves space and informs other developers of the limitations imposed on the variable.
I imagine one can use byte for anything dealing with actual bytes.
Also, the parts (red, green and blue) of colors commonly have a range of 0-255 (although byte is technically -128 to 127, but that's the same amount of numbers).
There may also be other uses.
The general opposition I have to using byte (and probably why it isn't seen as often as it can be) is that there's lots of casting needed. For example, whenever you do arithmetic operations on a byte (except X=), it is automatically promoted to int (even byte+byte), so you have to cast it if you want to put it back into a byte.
A very elementary example:
FileInputStream::read returns a byte wrapped in an int (or -1). This can be cast to an byte to make it clearer. I'm not supporting this example as such (because I don't really (at this moment) see the point of doing the below), just saying something similar may make sense.
It could also have returned a byte in the first place (and possibly thrown an exception if end-of-file). This may have been even clearer, but the way it was done does make sense.
FileInputStream file = new FileInputStream("Somefile.txt");
int val;
while ((val = file.read()) != -1)
{
byte b = (byte)val;
// ...
}
If you don't know much about FileInputStream, you may not know what read returns, so you see an int and you may assume the valid range is the entire range of int (-2^31 to 2^31-1), or possibly the range of a char (0-65535) (not a bad assumption for file operations), but then you see the cast to byte and you give that a second thought.
If the return type were to have been byte, you would know the valid range from the start.
Another example:
One of Color's constructors could have been changed from 3 int's to 3 byte's instead, since their range is limited to 0-255.
It means that knowing that a value is explicitly declared as a very small number might help you recall the purpose of it.
Go for real docs when you have to create a documentation for your code, though, relying on datatypes is not documentation.
An int covers the values from 0 to 4294967295 or 2 to the 32nd power. This is a huge range and if you are scoring a test that is out of 100 then you are wasting that extra spacce if all of your numbers are between 0 and 100. It just takes more memory and harddisk space to store ints, and in serious data driven applications this translates to money wasted if you are not using the extra range that ints provide.
byte data types are generally used when you want to handle data in the forms of streams either from file or from network. Reason behind this is because network and files works on the concept of byte.
Example: FileOutStream always takes byte array as input parameter.