byte 1 « byte « Java Data Type Q&A

1. Java: How to pass byte[] by reference?

You can do it in .NET by using the keyword "ref". Is there any way to do so in Java? Thanks in advance!

2. GZIPInputStream decompression did not work fine for the compressed data with length more than 532 bytes

I have created compression and decompression using gZipInputStream in java It works fine for small amount of data but if the data length after compression becomes greater thatn 532 then my decompression ...

3. How can I assign 2 bytes to a variable in Java?

How can I assign 2 bytes to a variable in Java? I know I can do this:

byte val = 2; // this is one byte with 0000 0010
But I need ...

4. Bytes in Java?

Thanks for all above answers but didn't really help me well just to give an idea what exactlty i wants to do: I am coding for some sort of packet which ...

5. Prepend zero to byte

I'm reading file and I want to print byte value in 2 digits if it is less than 10 (example if byte=1 it should disply byte=01), I don't want to compare ...

6. Java Syntax: byte f()[] vs. byte[] f()

Just noticed in ByteArrayOutputStream, the toByteArray() is declared as,

public synchronized byte toByteArray()[];
What's the difference between this declaration and the following one?
public synchronized byte[] toByteArray();

7. Counting Bytes sent/received over HTTP

In Java,
How could the bytes sent and received over an active HTTP connection be counted?
I want to display some statistics like:

Bytes Sent     : ...

8. Creating a byte[] from a List

What is the most efficient way to do this?

9. How to print bytes using System.out.println?

I've declared a byte array (I'm using Java):

byte test[] = new byte[3];
test[0] = 0x0A;
test[1] = 0xFF;
test[2] = 0x01;
How could I print the different values stored in the array? If I use System.out.println(test[0]) ...

10. Java readFile from byte x to byte y

Im trying to read a text file, x bytes at a time into a variable, process each "chunk" and write it to another file. So far all I can do sucessfully is:

// ...

11. C to Java port: calculating a 3 byte checksum

Does this seem correct? I'm trying to port this checksum method from C to Java but the values returned from my Java function are too high. I suspect the way I'm ...

12. java byte data type

In Sun' tutorial it says about a byte: 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 ...

13. Get bytes for a class that was generated at runtime

I am working with a Java framework that generates some (proxy) classes at runtime, using a custom ClassLoader. I would like to get for any such class that the custom ClassLoader ...

14. work sun.misc.BASE64Encoder/Decoder for getting byte[]

I am trying to use sun.misc.BASE64Encoder/Decoder, but this code:

(new sun.misc BASE64Encoder()).encode(new    
    sun.misc.BASE64Decoder().decodeBuffer("test string XML:"))
returns "test/string/XML/" I am embarrassed

15. How to get number of bytes?

How do I obtain the number of bytes before allocating the byte size of the array 'handsize' as shown below as the incoming ByteArray data are sent in 3 different sizes. ...

16. Problem sending bytes greater than 127 to Java Sound's SysexMessage

I'm doing some work with the JavaSound API to send a MIDI System Exclusive (Sysex) message to an external MIDI device (an electronic keyboard). According to the Yamaha manual, the data ...

17. decode encode between String and byte in java

byte[] bytes = new byte[] { 1, -1 };
System.out.println(Arrays.toString(new String(bytes, "UTF-8").getBytes("UTF-8")));
System.out.println(Arrays.toString(new String(bytes, "ISO-8859-1").getBytes("ISO-8859-1")));
[1, -17, -65, -67]
[1, -1]

18. byte toPositiveInt method

is there anything like this in JDK or Apache Commons (or in other jar)?

 * Return the integer positive value of the byte. (e.g. -128 will return
 * 128; -127 will ...

19. Creating 3DES key from bytes

I create a triple DES key from the a byte array ("skBytes") but when calling getEncoded on the triple DES key ("sk") and comparing it to the byte array, they differ! ...

20. Finding value of 2 bytes in Java

I am trying to find the value of the first 2 bytes in a UDP packet which corresponds to the length of the remaining payload. What is the best method to ...

21. chat program that sends bytes instead of string

I have a chat program I made a while ago for a class. I am trying to changes some parts of it and that includes sending bytes instead of strings. If ...

22. Generate X509Certificate from byte[]?

Is there a possibility to generate an from an byte[]?

23. Java Set of Bytes

Hello Can anyone help me to know how can I have a "Set" of Bytes in Java? Thank you

24. Truncating Strings in Java by Bytes

I create the following for truncating a string in java to a new string with a given number of bytes.

        String truncatedValue = ...

25. Endless for loop

I have the following loop:

for (byte i = 0 ; i < 128; i++) {
    System.out.println(i + 1 + " " + name);
When I execute my programm it ...

26. Why does java have no byte type suffix?

So java has a long type suffix for literals: (123L), a double type suffix (43.21D), a floating point suffix (1.234F). So ... why no byte type suffix? For example, ...

27. bytes of a string in java?

In java if i have a String x how can i calculate the number of bytes in that string?

28. Really simple question about creating non-standard sized byte groups

So for a project that space really matters in, I'd like to be able to write to a file a number which takes up THREE bytes. So essentially, an unsigned type ...

29. Generate 8-byte number in Java

I'm a little bit confused, how to do this. I know I can use Random class to generate random numbers, but I don't know how to specify and generate 8-byte number? Thanks, Vuk ...

30. Java stripping zeros from function

I'm trying to flip some bytes around in Java and the function I have is working correctly for some bytes and failing for others. The function I am using is this:

public static ...

31. How do I append a byte[] to a List?

How do I append the elements of a byte[] to a List<Byte>?

32. Get byte[] from List

Possible Duplicate:
Creating a byte[] from a List<Byte>
I have List list. How to get byte[] ( subarray of list ) from startIndex to endIndex id ...

33. Byte alignment problem using Preon

Hello everybody :) I am currently using preon for a spare time project, and I have encountered the following problem: I am trying to read a fixed length String with the following ...

34. why byte += 1 compile but byte = byte + 1 not?

If I have a byte variable: byte b = 0; why does the following work:

   b += 1; // compiles
... but this does not ?

35. if I have a classloader instance, can I find where it looks for the class bytes?

if I have dira,jarb and dirc in the classpath in that order, and I have a java app with 3 classloaders with a parent/child/grandchild relationship, will they all read the same ...

36. Immutable container for a byte[] that supports subsequences, like String.substring()

String.substring() efficiently reuses the underlying char[] within the String object, I'm wondering if there is an immutable container for byte[] arrays that supports a similar kind of efficient reuse of the ...

37. LRU byte Cache java

I need to implement a cache in java with a maximum size, would like to do it using the real size of the cache in the memory and not the number ...

38. Accessing Java byte[] in C++

I have a Java application that persists byte[] structures to a DB (using Hibernate). I'm writing a C++ application that reads these structures at a later time. As you might expect, ...

39. How can I use a part of byte[] without arraycopy?

I wonder how to use a part of byte[] without arraycopy? In C Language

char buf[100];
int i;

for (i = 0; i < 100; i += 10) {
    proc(buf + i);
But ...

40. Is it possible to perform XOR operation on 4bytes at a time

i need to perform XOR operation on 4 bytes which are represented as a single byte

int temp=0;
int temp1=0;
int temp2=0;
int temp3=0;
int temp4=0;
i have used the above code to convert the four bytes ...

41. Can we multiply two bytes directly by using * operator directly

I need to perform the following operation on a byte (2*x*x)+x where x is a single byte. Can i perform that operation directly as we will do for int. ...

42. Are there any real life uses for the Java byte primitive type?

For some inexplicable reason the byte primitive type is signed in Java. This mean that valid values are -128..127 instead of the usual 0..255 range representing 8 significant bits in ...

43. Checing if FTPClient download has recieved all bytes

I download an image file from an FTP Server using FTPClient. My look like this:

public class FtpDownloadDemo
 public static void main(String[] args)
  FTPClient client = new FTPClient();
  FileOutputStream ...

44. different compiler behavior when adding bytes

byte b1 = 3;
byte b2 = 0;

b2 = (byte) (b2 + b1);  // line 3

b2 = 0;
b2 += b1;            ...

45. Is there something like bytes(byte...b):byte[]?

i am looking for a simple method were i can pass in some bytes, as varargs, and get a byte[] returned, like:

static byte[] byteArray(byte ...bytes){ return bytes;}
What i found so far... java.lang.Byte ...

46. Java handling billions bytes

I'm creating a compression algorithm in Java; to use my algorithm I require a lot of information about the structure of the target file. After collecting the data, I need to reread the ...

47. Java, load jar bytes and use it

Is there a way to load a crypted file (that is a jar file), decrypted it (so obtains the real byte array) and use it without create a file on filesystem ...

48. JAVA - SHA256 of concatenation byte+string+byte

JAVA - SHA256 of concatenation byte+string+byte 1) if in php i've

$var = "\x00\x23\x21\x11";
how i should write this statement in java? ....
2) so i need to concatenate 3 types of variables, two of this ...

49. Java byte value not correct

I have this hex value 93 which in decimal value should be 147. Since this number is less than 255, it is representable in a byte. In java I did this

System.out.println((new Integer(1)).byteValue()); ...

50. No number of bytes received in java

I would like to determine the number of bytes downloaded from the following working URL connection: I have following code to implement:

   HttpURLConnection connection = (HttpURLConnection) url.openConnection();

51. Format String in Java regarding its length in bytes

Let's say I have a String containing non ASCII characters in Java and I want to use String.format() to set it so the formatted String will have a minimum width regarding ...

52. How to write bytes by byte and display it continuously

I have encrypted video file and while decrypting it i have defined Bytebyte[] input = new byte[1024]; size to written it in output file. Here i want to write first 1024 bytes ...

53. Method string to byte

I spend all the day trying to find the answer, so finally I write here. I encrypt one string with class crypto and I get a byte[]. I have to convert this byte ...

54. Print String as Bytes

Can somebody tell me how to print a string as bytes i.e. its corresponding ASCII code?! My input is a normal string like "9" and the output should be the corresponding ASCII ...

55. Issue in decompressing bytes

56. byte stuffing

the 'f' is added at the start and end of the string to indicate the beginning and end. if there is an 'f' in the actual string you place an 'e' ...

57. a little BYTE of problem....

58. Method.getReturnType() and byte[]

59. Problem sending bytes.

60. Display byte[] in browser

61. why am I getting NumberFormatException with Byte.parseByte()?

I'm trying to convert a long or int to a byte array. I'm restricted to using Java 1.3. I'm first trying to use Long.toBinaryString(myLong), and then pass 8-character substrings into Byte.parseByte(mySubstring, 2), but I'm getting errors like: java.lang.NumberFormatException: Value out of range. Value:"11110100" Radix:2 What am I doing wrong? A byte is 8-bit, two's complement right? So shouldn't it be able ...

62. From Byte[] to Ascii text String

I have a byte array created from an ASCII/HEX string and I have the ability to pull out a bunch of bits through bit shifting, and up till recently I was storing these values in a Long variable. However When it comes to taking these values and storing them in a string and printing them to some kind of Output as ...

63. How to format a byte as %02X?

Hi, I was wondering how you guys would print a byte, to a stream or writer as 2 hexadecimal digits? Or more precisely, a byte array as a sequence of hexadecimal digits? Without big cats (must run on java-1.4.2 or older)? I have been looking at formatters for a bit, but it seems to me that the easiest way would be ...

64. Interesting problem with byte

Hi, This is one of the advantages of the Compound Assignment Operator += When you do any integer arithmetic with byte values, the compiler expects you to put an explicit cast before assigning the result to a byte variable. For example, byte a = 3; a = a + 5; //won't compile, //needs an explicit cast a = (byte) a + ...

65. Addition of two byte[]

Hi Everyone, Is it possible that i can add two arrays. For example, I had two array of type byte[] bArray1; and byte[] bArray2; Then what is it ok if i do bArray2 = bArray1 + bArray2; When I am doing this. I am getting an error saying that"The operator + is undefined for byte[],byte[] Can anyone please explain me how ...

66. Left Shift of byte

Hi all, When a left shift is performed on a byte it is first promoted to an int. When you want the result of the shifted byte value is it true that you must discard the top three bytes of the int result?. Is this because the top three bytes are used only for representing the sign of a byte or ...

67. Printing the value of a byte as a hexstring

I want to convert a byte[] array to a hexstring. I have no problem iterating through the array. However, the only way I have found to convert an integral data type to a hexstring is by using Integer.toHexString() or Integer.toString(int i, int radix). There are two problems I would like to address by using these methods: 1) Neither method pads with ...

68. interger to a byte

69. javac thinks byte[] is a String

[Joe]: I know that I don't find a String where byte[] is required in that code. And yet, it's there. byte[] h = Base64.encode(new byte[5]); The left hand side is saying it expects a byte[]: byte[] h = On the right hand side, this part here is indeed a byte[]: ...

70. Help! Byte from ByteArrayInputStream to ByteArrayOutputStream converted to -1!!

I've got an image saved into a ByteArrayInputStream. At a certain point in the code, the bytes in that inputstream are written to a ByteArrayOutputStream. Later, they are then read again from that outputstream. For some reason, when they're read out of the outputstream, the bytes are all wrong. They're converted into many weird numbers including many negative ones (such as ...

71. byte data type

72. Masking a byte

import java.math.BigInteger; public class MathsExp { public static void main(String[] args) { byte b1 = (new BigInteger("2")).pow(8).intValue() - 1; System.out.println("b1 " + b1); System.out.println("Masked b1 with 0xFF " + (b1 & 0xFF)); System.out.println("Masked b1 with 0xFFFF " + (b1 & 0xFFFF)); } } Output: b1 -1 Masked b1 with 0xFF 255 Masked b1 with 0xFFFF 65535 The first line of the ...

73. decompressing byte[]

hi, sorry for taking your time. however i am encountering problem reguarding compress and uncompressing of byte[]. below is the codes i used for compression ---------- baos = new; try { oos = new; oos.writeObject(object); } catch ( ioe) {, ioe.getMessage()); } byte[] bytearr = baos.toByteArray(); Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION); deflater.setInput(bytearr); deflater.finish(); deflater.deflate(bytearr); byte[] compressedByte ...

74. Shifting a byte and getting negative answer!

First of all, parse and println works in decimal, so it will not treat what you have as binary nor will it print out as binary, in the way that you have it written. Anyway... 100 (decimal) ==> 0110 0100 (binary) shift left by 2 ==> 1001 0000 this is a negative number due to the sign bit, we can take ...

75. Byte[] to Video Playback

76. Taking a byte

A byte has 8 bits. The Most Significant Bit (MSB) or the leftmost bit represents the sign: 0 for positive and 1 for negative. That leaves you with 7 bits to represent the magnitude. Negative numbers are represented in two's-complement. -128 is the biggest negative number that can be represented by 8 bits, twos-complement while 127 is the biggest positive number ...

77. byte data type behavior

Hi, I have this simple program from a java book byte b1=0x7f; byte b2=0xf4; int i1 = (b1 << 8) | (b2 & 0xff); System.out.println("Integer is: " + i1); When I compile this with my javac it comes back with the error message 1 error byte b2=0xf4; ^ expected byte found int, possible loss of precision. (Something like that). I can't ...

78. Bytes of junk

Hi, I'd like to create a byte array of a specified size and fill it with noise/junk characters/nonsense/whatever. I'm acting under the assumption that if I don't initialize the array, it will hold null at all positions and throw an exception as soon as I try to do anything with it. If that's true, can someone help me figure out how ...

79. (byte) and 0xff

80. Question regarding Byte.MAX_VALUE

Originally posted by Thomas Markl: // Byte.MAX_VALUE + 1 ) == Byte.MIN_VALUE results in comparison // of 128 to -128. Why is this true and direct comparison of // (-128 == 128) is false? public class Test63 { public static void main(String args[]) { System.out.println ( ( byte ) ( Byte.MAX_VALUE + 1 ) == Byte.MIN_VALUE ); System.out.println ( Byte.MAX_VALUE+1+ ""+ ...

81. After an overflow, a byte gets set to a negative value?

1: void infiniteLoop() 2: { 3: byte b = 1; 4: 5: while ( ++b > 0 ) 6: ; 7: System.out.println("Welcome to Java"); 8: } because there is nothing there before the ';' on line six, nothing gets done while b is larger than 0. But then b gets past 127 in value and suddenly b gets reset!! And then ...

82. byte datatype!

The byte datatype is needed to store integer values within range in the least amount of memory. A JVM might be implemented on processors with smaller than 32-bit registers, and memory resources are not always abundant. Not many people "have" to use bit-shifting in "normal" coding. It's been a while, but IIRC some compression algorithms use bit-shifting. I'm sure there are ...

83. How to print out # of bytes used

84. bytes in Java

Hi guys, This must seem extremely silly and less than basic!!! But seriously how does an int get stored in a byte data type. How does the truncation happen? What info I have is that it divides the int(if > than 256) by 256 and stores the remainder in the byte. But what happens if I want to store a value ...

85. Concatenate two bytes

I'm not sure how to do this, so I thought I'd ask here, I'm digging through and doing research, but right now I'm pretty stuck. Here's what I need to do: take to bytes, concatentate them together (not add), for example, so that (byte)0x40 and (byte)0xFF become (short)0x40FF. If I try to concatenate the two bytes as strings, I get a ...

86. Can a Byte be converted to String?

87. String to byte? and string to byte[]?

Oups, should have explained myself better... Ok, i have this String which is in fact a SQL command i get from an interface. I have to send it to other users by using Spread, which is a group communication tool. My problem was that the function i needed had a byte[] as its argument, so thats why i needed converting the ...

88. Storing really big numbers (i.e. 640 bytes)

A long is pretty long, but not long enough. I'm working on cryptography right now and I'm trying to figure out how to store very large numbers (with 250 or so digits) using primitive or non-primitive data types. If I was to use a non-primitive data type, could I still do basic mathematical computations with it? How would I go about ...

89. Passing a byte as a parameter

90. Byte Manipulation

Is there a page or documentaion that shows information regarding the primitive data type byte and byte array? The API falls short and I need to manipulate unsigned bytes for a project. Project is not due for a while so I have some time but I was just looking into the subject and there is a total lack of reference material. ...

91. Byte Operation

Originally posted by Saravana Ranch: I got a integer string of size 10 (initialized with 0 )then I want to add a number with this string which is preceded with zero (0), using byte operation is it possible. Example : a[10] which is initialized with zero. I want to add 123 in this then result should be like this. 0000000123. ( ...

92. Java Bytes

Hi everyone, Consider the below program public class ByteTest { public void ByteTest1() { byte byte1 = (byte)0x9C; Byte byte2 = new Byte(byte1); System.out.println(byte2.toString()); } public void ByteTest2() { byte byte3 = 0x5A; Byte byte4 = new Byte(byte3); System.out.println(byte4.toString()); } public static void main(String[] args) { ByteTest a = new ByteTest(); a.ByteTest1(); a.ByteTest2(); } } Now from what i understand 1 ...

93. byte problem

94. Byte Problem

95. How I get byte[ ] from Object?

Well, a byte array is an object, so... if this object that is referred to is a byte array, then you can simply cast it back to a byte array reference before you use it. However, if this object is not a byte array, then it would depend on what this object is. Is there a method that will return the ...

96. Byte Primitive type

Hi all, I am trying to understand how the primitive byte works. Can someone explain to me why this code is not working. package tut.intf; public class Window implements WinInterface{ byte size; String colour; String shape; public void setSize(byte s){ size=s; } void setColour(String c){ colour=c; } void setShape(String s){ String a= "j"; shape=s.concat(a); } public static void main(String args[]){ Window ...

97. byte type

98. Byte

Hi sumaraghavi, it doesn't compile because if you add two bytes the result in general doesn't fit into a single byte. This could easily produce an overflow so the compiler doesn't allow it. You have to keep in mind, that the compiler ignores the values used in your code. For you it's obvious that 3+8 fits in one byte but the ...

99. Encryption-decryption loosing bytes in operation

Here is my encryption/decrypt code. But after decrypting file, it is some bytes bigger or smaller, i dont know how to get the exact bytes. import; import; import; import; import; import; import; import; import; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import sun.misc.BASE64Decoder; ...

100. Byte

No, this does not work like that. You have to substract 1, and inverting all bits Traditional, with Twos complement, to negate a number, you invert then you add one. This should work in both directions -- obviously, as negate is an operation that works in both directions. As Christophe said, you can also "subtract one and invert", which is the ...