Arun Abraham
Arun Abraham

Reputation: 4037

byte hex calculation in java

i am an amature in byte..hex calculation etc...my application requires me to send some data through sockets in the form of bytes...

1st byte -> [ { ]
2nd byte -> [ { ]
3rd byte  -> [ 0xD1 ]
4th byte -> [ 0x00 ]
5th byte -> [sum of first,second and third hex value]
6th byte -> [ } ]
7th byte -> [ } ]

This is a sample How can i perform such an operation of assigningthe hex values in each byte, storing these bytes in an array.. I got a bit stuck up with this.. could someone help me out ???

Upvotes: 1

Views: 3745

Answers (3)

michal.kreuzman
michal.kreuzman

Reputation: 12410

you can build up array of bytes like :

    byte[] data = new byte[7];

    data[0] = "{".getBytes()[0];
    data[1] = "{".getBytes()[0];
    data[2] = (byte) 0xd1;
    data[3] = (byte) 0x00;
    data[4] = (byte) 0xd1 + 0x00;
    data[5] = "}".getBytes()[0];
    data[6] = "}".getBytes()[0];

Upvotes: 0

BlueMonkMN
BlueMonkMN

Reputation: 25601

People often confuse the representation of a number with the value of a number for some reason. The values you are adding are not hexadecimal or decimal or binary. They are just numbers. A byte is a byte. You can just add two bytes with + and there's nothing magical about it. It works the same whether you show the results as hex or decimal or anything:

Example:

  0x2A (42)
+ 0x13 (19)
= 0x3D (61)

Upvotes: 1

Vance Maverick
Vance Maverick

Reputation: 822

Hex is just a notation for the value in the byte. Add them together using ordinary +.

Upvotes: 1

Related Questions