0

I've a newbie question about Java type manipulation. I want to split a float variable and an int variable into bytes.

My question is, how I can split this variables?

Something like this:

int or float variable = 1000;

byte variable_byte[3];

variable_byte[0] = 0x00;
variable_byte[1] = 0x00;
variable_byte[2] = 0x03;
variable_byte[3] = 0xE8;
Singee
  • 523
  • 2
  • 6
  • 16
  • 1
    Not 100% clear what you mean by "splitting" the variable, but if you want to convert an integer to bytes, check out this: http://stackoverflow.com/questions/2183240/java-integer-to-byte-array – Stephen Rosenthal Jan 26 '16 at 17:13

2 Answers2

0

I will be better to find other way to do what you are trying to.. but here is what you are looking for:

int value = 100;
byte array = new byte[3];
int i=0;
while(value>0){
  cont[++i]=(byte)(value%10);
  value=value/10;
}
0

You can do something like this given both int and float are four bytes

    byte[] iBytes = ByteBuffer.allocate(4).putInt(1000).array();
    System.out.print(String.format("%2X:%2X:%2X:%2X\n", 
            iBytes[0], iBytes[1], iBytes[2], iBytes[3]));
    float myFloat = (float) 100.23;
    byte[]fBytes = ByteBuffer.allocate(4).putFloat(myFloat).array();
    System.out.print(String.format("%2X:%2X:%2X:%2X\n", 
            fBytes[0], fBytes[1], fBytes[2], fBytes[3]));
Aniruddh Dikhit
  • 662
  • 4
  • 10