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

Monday, September 26, 2022

[FIXED] How to write and read bytes from unsigned variable

 September 26, 2022     binaries, c++, short, unsigned     No comments   

Issue

Here is what I'm trying to do:

I have two integers

int a = 0; // can be 0 or 1
int b = 3; // can be 0, 1, 2 or 3

Also I want to have

unsigned short c

to store that variables inside it.

For example, if I would store a inside c it will be looking like this:

00000000
^ here is a

Then I need to store b inside c. And it should look like following:

011000000
 ^^ here is b.

Also I would like to read that numbers back after writing them. How can I do this?

Thanks for your suggestions.


Solution

Assuming those are binary representations of the numbers and assuming that you really meant to have five zeros to the right of b

01100000
 ^^ here is b

(the way you have it a and b overlap)

Then this is how to do it

// write a to c
c &= ~(1 << 7);
c |= a << 7;

// write b to c
c &= ~(3 << 5);
c |= b << 5;

// read a from c
a = (c >> 7)&1;

// read b from c
b = (c >> 5)&3;


Answered By - john
Answer Checked By - Clifford M. (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