How to write and read bytes from unsigned variable - c++

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.

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;

You can accomplish this with C++ Bit Fields:
struct MyBitfield
{
unsigned short a : 1;
unsigned short b : 2;
};
MyBitfield c;
c.a = // 0 or 1
c.b = // 0 or 1 or 2 or 3

Related

Find the remainder after dividing the sum of two integers by the third

I'm trying to find a solution to a task. My code passed only 3 autotests. I checked that the solution satisfies the max/min cases. Probably there are situations when my code is not valid.
Description of the task: Find the remainder after dividing the sum of two integers by the third.
Input: The first line of input contains two integers A and B (-10^18 ≤ A, B ≤ 10^18). The second line contains an integer C (2 ≤ C 10^9).
Output: Print the remainder of dividing A + B by C.
My code:
#include <iostream>
// int64_t
#include <cstdint>
#include <stdint.h>
// #include <math.h>
// 3 tests passed
int main() {
int64_t a, b, c;
std::cin >> a >> b >> c;
// a = pow(-10, 18);
// b = pow(-10, 18);
// // c = pow(10, 9);
// c = 3;
// c = pow(10, 18) - 20;
// c = 1000000000000000000 + 1;
// c = 1000000000000000000 + 2;
// std::cout << a << std::endl;
// std::cout << b << std::endl;
// std::cout << c << std::endl;
std::cout << (a + b) % c << std::endl;
return 0;
}
Please note that in C++ reminder for negative values:
was implementation defined until C++11
integer division is rounded towards zero since C++11 which makes reminder negative sometimes.
Now most probably in your task modulo result should be always in range <0, C) (or written differently <0, C - 1>). So to handle cases where A + B is negative, you have to take this into account that reminder may be negative.
So your code can look like this:
nt main() {
int64_t a, b, c;
std::cin >> a >> b >> c;
std::cout << (a + b) % c + ((a + b) % c < 0) * c << '\n';
return 0;
}
Which basically adds c to result if result is negative and makes result inside required range. (assuming c is positive).
Modulo operation in C++ uses truncated division, i.e., the result of x % y is negative if x is negative.
To obtain a non-negative result congruent to (a + b) % c, you can use ((a + b) % c + c) % c.
I believe the point of the exercise is to handle overflows and underflow by realizing that the remainder of the sum is the sum of the remainder modulo c.
That's what my magic-8 ball says anyway. If that's not the solution the provide the failed input and expected and actual output.

Combining Bits - Combining Characters to Integers C++

I have an idea on how to make a header of a file more efficient (for an assignment) but I want to know if I can carry out the implementation.
Is it possible to read 24 bits from a file and then put it into an integer and have it retain its value?
Let's say I have:
00000000 00000001 00000000 = 256
Can I read this from a file, separate it into three characters, and then combine these characters into one integer such that the value 256 is retained? Such that the end result would be:
00000000 00000000 00000001 00000000 = 256
unsigned char a, b, c;
if (f >> std::noskipws >> a >> b >> c)
{
int n = a * 256 * 256 + b * 256 + c;
// use n...
}
else
std::cerr << "unable to read 3 characters from file\n";
Try this:
int combine_chars(char a, char b, char c) {
char arr[4] = {c, b, a, '\0'};
return *(int *)arr;
}
This is assuming little-endian representation of the integer, which means that the least significant byte has the smallest index. Basically the function creates an array of the 3 characters with a trailing 0 (since the most significant byte is '\0', or most significant 8 bits are 0). The least significant byte is c, then since the second least significant byte is 1 from the example, that becomes 1 << 8 which is 256. The array in memory is:
c b a '\0'
This then gets casted to an integer pointer (int *) which then gets dereferenced to the integer value and returned.
you can try something like this:
int getNumberFromStdin() {
std::string numberStr;
for (int i = 0; i < 3; ++i) {
std::string s;
std::cin >> s;
numberStr += s;
}
int number = 0;
for (const auto c : numberStr) {
number = (number << 1) + (c - '0');
}
return number;
}

XOR conditionally without branching if the lowest bit is set

I have three unsigned 32-bit integers, say a, b, and c. If the lowest bit of b is 1, I want to XOR c with a, and store the result into c. We can do this in the following way:
#include <cassert>
int main()
{
// Some values for a and c
unsigned a = 16;
unsigned c = 25;
unsigned b = 5; // 101_2
if(b & 1)
{
c ^= a;
}
assert(c == 9);
}
Can I do this conditionally without branching, that is, with no if-statements?
There's lots of ways to do this.
Here's another, no multiply, only 4 operations.
c ^= a&(-(b&1));
This should work
c ^= a * ( b & 1 );
Without if statement and without branching you have to check the assembly dump of your compiler:
c ^= ~((b & 1) - 1) & a;

Flags using Bits

I'm trying to do simple bit operations on a 'char' variable;
I would like to define 5 constants.
const int a = 0;
const int b = 1;
const int c = 2;
const int d = 3;
const int e = 4;
When I try to set more than one bit of the char, all bits apparently up to the set bit a read as set...here is code I use to set and read bits of the char var:
char var = 0;
var |= c;
var|= d;
BOOL set = false;
if(var & b)
set = true; // reads true
if(var & c)
set = true; // also reads true
if(var & d)
set = true; // also reads true
I read an incomplete thread that says that the operation to set bits may be different for x86...the system I'm using...is that the case here?
You're cutting into your other "bits"' space. Examining a couple gives us:
b = 1 = 0001
c = 2 = 0010
d = 3 = 0011 //uh oh, it's b and c put together (ORed)
To get around this, make each one represent a new bit position:
const int a = 0; //or 0x0
const int b = 1; //or 0x1
const int c = 2; //or 0x2 or 1 << 1
const int d = 4; //or 0x4 or 1 << 2
const int e = 8; //or 0x8 or 1 << 3
You should consider not using 0 if there's a possibility of no bits being set meaning something different, too. The main application for this is to set and check flags, and no flags set definitely shows independence.
Change your definitions to because they way you have defined it some of them has more than one bit set
const int a = 1 << 0;
const int b = 1 << 1;
const int c = 1 << 2;
const int d = 1 << 3;
const int e = 1 << 4;
This way it is evident that each constant only has 1 bit set.
If you want to learn all about the various bit hacks...

Converting a set of booleans to a number

This is the code I am going to use to take a set of three booleans and convert it into an int for a switch statement:
int bits = 0;
bool a = true, b = false, c = true; // 101 = 5
bits = bits | a << 2;
bits = bits | b << 1;
bits = bits | c;
cout << bits;
I have eight cases based on the combined state of these three booleans. Am I doing this right?
Right, not in the sense of the syntax although if there are any problems there please advise. More right in the sense of "Is this the best way to solve this problem?"
If you are using C++, you could use bitset<N>.
You're doing it right. You could make the code a little more succinct though:
bits |= (a<<2) | (b<<1) | (c<<0);
Just be aware that the Standard doesn't enforce any size constraint on bool. Pragmatically speaking there shouldn't be a problem with three bits, but the Standard doesn't back you here.
$ cat ttt.c
//example of C solution
#include <stdio.h>
int main() {
union {
unsigned int val;
struct {
unsigned a : 1;
unsigned b : 1;
unsigned c : 1;
//unsigned d : 1;
//e, f, g, h...
} flags;
} bits;
bits.val=0;
bits.flags.a = 1;
bits.flags.c = 1;
printf("val: %d\n",bits.val);
return 0;
}
~$ ./ttt
val: 5
I would do it as:
bits = (bits << 1) | a;
bits = (bits << 1) | b;
bits = (bits << 1) | c;
which would require less maintenance work if you needed to add or to remove a flag.
However, doing this so that you can use it for a switch sounds like it might be a bad idea. Adding a flag would double the number of states you'd need to handle, and the case values would be fragile and hard to read.
But if you really must, here's another approach:
enum
{
c_bit_offset,
b_bit_offset,
a_bit_offset
};
unsigned int bits = (a << a_bit_offset)
| (b << b_bit_offset)
| (c << c_bit_offset);
switch (bits)
{
case 0:
/* Do something. */
break;
case (1 << a_bit_offset):
/* Do something. */
break;
case (1 << a_bit_offset) | (1 << b_bit_offset):
/* Do something. */
break;
...
}
By the way, you probably should use unsigned int instead of int.
You can make some defines to make easy to work with bits
#define BitSet(arg,bit) ((arg) |= (1<<bit))
#define BitClr(arg,bit) ((arg) &= ~(1<<bit))
#define BitFlp(arg,bit) ((arg) ^= (1<<bit))
#define BitTst(arg,bit) ((arg) & (1<<bit))
Then you can use only one char
keys = 0b00000101;
BitSet (keys,1);
This an common way to work in embedded systems.
You can always do the conversion explicitly:
bits = bits | (a ? 1 : 0) << 2;
However I believe C/C++ will handle it implicitly, once you're using the bit-shift operator.
You should define constants for each flag, giving a name to the bit you are setting:
const int a_flag = 2;
bits = bits | (a ? 1 : 0) << a_flag;
Edit:
As you can see from the comments on my answer, most C/C++ programmers prefer to learn implicit conversions and operator precedence. Therefore your original code is "most correct".
Edit 2:
Except, you should use the |= operator:
const int a_flag = 2;
bits |= a << a_flag;