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

Wednesday, July 20, 2022

[FIXED] How to form 32 bit integer by using four custom bytes?

 July 20, 2022     bitwise-operators, byte, c#, integer     No comments   

Issue

I want to create a 32 bit integer programmatically from four bytes in hex such as:

Lowest byte is AA

Middle byte is BB

Other middle byte is CC

Highest byte is DD

I want to use the variable names for that where:

byte myByte_1 = 0xAA
byte myByte_2 = 0xBB
byte myByte_3 = 0xCC
byte myByte_4 = 0xDD

So by using the above bytes and using bitwise operations how can we obtain: 0xDDAABBCC ?


Solution

You can construct such int explicitly with a help of bit operations:

int result = myByte_4 << 24 | 
             myByte_3 << 16 | 
             myByte_2 << 8 | 
             myByte_1;

please, note that we have an integer overflow and result is a negative number:

Console.Write($"{result} (0x{result:X})");

Outcome;

-573785174 (0xDDCCBBAA)

BitConverter is an alternative, which is IMHO too wordy:

int result = BitConverter.ToInt32(BitConverter.IsLittleEndian 
  ? new byte[] { myByte_1, myByte_2, myByte_3, myByte_4 }
  : new byte[] { myByte_4, myByte_3, myByte_2, myByte_1 });


Answered By - Dmitry Bychenko
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

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