PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

[FIXED] How to find the Lower and Upper Byte from Hex value in PHP?

 July 22, 2022     php, php-5.4, php-7, php-7.2     No comments   

Issue

I have a series of Hex values like 0x1b12, 0x241B, 0x2E24, 0x392E and I need to calculate the Lower byte and Upper Byte from each of these hex values for further processing. How can I do that? I did a bit of research and saw that there is an unpack function in php but the "format" part in the argument is making me confused. Some of the unpack code that I've seen is added below.

unpack("C*",$data)
unpack("C*myint",$data)
unpack("c2chars/n2int",$data)

As mentioned the aforementioned code, I don't quite understand what "C*","C*myint","c2chars/n2int" does in the unpack function. So I'm not quite sure if I can use unpack as the solution to my problem. Your help is much appreciated.

Thanks in advance.


Solution

You can do this with the pack function. It is easier and faster with Bitwise Operators:

$val = 0x1b12;  //or $val = 6930;

$lowByte = $val & 0xff;  //int(18)
$uppByte = ($val >> 8) & 0xff;  //int(27)

The code needs an integer $val as input. If a string of the form "0x1b12" is available as input, then this must be converted into an integer:

$stringHex = "0x1b12";  //or "1b12"
$val = hexdec(ltrim($stringHex,'0x'));

ltrim is required so that no depreciation notice is generated from 7.4.0 onwards.



Answered By - jspit
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing