Jump to content

Convert Java Code to PHP: Convert signed hex value to big-endian binary?


sookyboo

Recommended Posts

Anyone know how to convert this java code to php?

 

// Take the signature passed, a signed hexadecimal value and

// and convert to a byte array in 2's compliment, big-endian.

// We wrap in a try-catch in case the signature is not a signed

// hexadecimal number

byte[] barray = new BigInteger(signature,16).toByteArray();

 

Thanks in advance :)

Link to comment
Share on other sites

Try this:

 

$hex = $argv[1];

function hex_to_bytes($hex) {
  $intval = base_convert($hex, 16, 10);
  $mult = 1;
  $bytes = array();
  while ($intval > 0) {
    $bytes[] = $intval % 256;
    $intval = floor($intval / 256);
  }
  $bytes = array_reverse($bytes);
  return $bytes;
}

$bytes = hex_to_bytes($hex);
print "{$argv[1]} => " . implode(',', $bytes) . "\n";

 

It's written to run as a CLI script, but you can extract the function.

Link to comment
Share on other sites

thanks I tried:

base_convert($hex, 16, 2);

The binary value is shorter than the hex value though... so... I am npt sure if its right...

 

I can only test if it really is the right value after I encrypt it, which I am also having trouble with :(

Thanks very much for the help though

 

http://www.phpfreaks.com/forums/index.php?topic=168552.new;topicseen#new

Link to comment
Share on other sites

Are you looking for a bit array or byte array?

 

The value is probably shorter because the result is not fixed width.  Eg, if you convert hex "10" then you will get binary "10000", not binary "00010000".  You can pad it afterwards.

 

Also heed the warning on the base_convert() description - if you use this function for values greater than your int size (probably 32 bit) then it will use floating point, and you will lose precision.  So you must do the conversion in small enough chunks.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.