How to split an int - c

I want to read in an int. For example 001. After I want to cut up the into so that A = 0, B = 0 and C = 1. I want to do this in C. Thanks!

If 001 is a bit representation of your integer value I, then:
int A = (I >> 2) & 0x1
int B = (I >> 1) & 0x1
int C = I & 0x1

You can achieve the result wanted by using modulus operator (%) and integer division (/). It's easier to understand than bitwise operators when you're starting to learn C.
scanf("%d", &i);
a = i / 100;
b = (i % 100) / 10;
c = (i % 100) % 10;

Building on Karl Bielefeldt's comment:
You can create a union of a char and a bitfield such as:
typedef union
{
unsigned char byte;
unsigned char b0 : 1;
unsigned char b1 : 1;
unsigned char b2 : 1;
unsigned char b3 : 1;
unsigned char b4 : 1;
unsigned char b5 : 1;
unsigned char b6 : 1;
unsigned char b7 : 1;
}TYPE_BYTE;
TYPE_BYTE sample_byte;
...then assign a value to sample_byte.byte and access each individual bit as sample_byte.b0, sample_byte.b1, etc. The order in which the bits are assigned is implementation dependent--read your compiler manual to see how it implements bitfields.
Bitfields can also be created with larger int types.
Edit (2011-03-15):
Assuming that maybe you want to read in a 3-digit base-10 integer and split the three digits into three variables, here's some code that should do that. It hasn't been tested so you might need to do some tweaking:
void split_base10(const unsigned int input, unsigned int *a, unsigned int *b, unsigned int *c)
{
unsigned int x = input;
*c = x%10;
x /= 10;
*b = x%10;
*a = x/10;
}
Good luck!

Related

Rotation of binary number in C

I have an issue i can't solve. The code below should get a number from the user and a number of rotations. The code should calculate the number after the rotations. For negative number of rotations the code should rotate the number left and for positive number of rotation the code should rotate the number right.
For example: for the input x=1010111011111011
my_rotate(x, -3) will return 0111010111011111
my_rotate(x, 3) will return 0111011111011101
Here is the code i wrote so far:
#include <stdio.h>
unsigned short my_rotate(unsigned short, char);
int main()
{
unsigned short num, res;
char rotations;
printf("\nPlease enter a number and number of rotations\n");
scanf("%hu %d", &num, &rotations);
res = my_rotate(num, rotations);
return 0;
}
unsigned short my_rotate(unsigned short a, char b)
{
unsigned short bitsNum = sizeof(unsigned short) * 8;
unsigned short temp1, temp2, result;
if(b == 0)
return a;
else if(b < 0)
{
temp1 = a << (bitsNum + b);
temp2 = a >> (-b);
result = temp1 + temp2;
}
else /* b > 0 */
{
temp1 = (a >> (bitsNum - (unsigned short)b));
temp2 = (a << (unsigned short)b);
result = temp1 + temp2;
}
return result;
}
I always get 0 as a result and i don't know why. What's wrong with my code?
in main :
unsigned short num, res;
char rotations;
printf("\nPlease enter a number and number of rotations\n");
scanf("%hu %d", &num, &rotations);
the last argument of scanf must be a pointer to an int (format is %d) but you give the address of a char, the behavior is undefined. Use an int for rotations for the format %d
In my_rotate b is a char and you do if(b < 0), the result depends if the char are signed or not, type n with signed char if you expect a char to be signed
If rotations is an int and b a signed char :
44795 (1010111011111011) and -3 produce 30175 being 111010111011111
44795 (1010111011111011) and 3 produce 30685 being 111011111011101
as you expected.
Note for me an unsigned short is on 16 bits, of course the result is not the same if short are on a different number of bit.
#bruno well explained a problem with input.
A rotation count may exceed +/- bitsNum, so a good first step is to limit the rotation count.
unsigned short my_rotate(unsigned short a, int b) {
unsigned short bitsNum = sizeof(unsigned short) * 8;
//add
b %= bitsNum;
....
Highly portable code would not use bitsNum as that is derived by the size of unsigned short (and assumes 8 bits/char) and an unsigned short could have padding bits. Certainly this is more of a rare machine concern. Code should derive the bit width based on USHRT_MAX instead.

store bits(byte) in long long by concatenation

poly8_bitslice() array if char as input, this input will be converted to bits(byte) by the function intToBits().
After the conversion I want to store the result in a long long variable. Is this possible?
Can I concatenate the result of intToBits()?
I want to do this with the following code:
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <string.h>
//#include <math.h>
typedef unsigned char poly8;
typedef unsigned long long poly8x64[8];
void intToBits(unsigned k, poly8 nk[8]) {
int i;
for(i=7;i>=0;i--){
nk[i] = (k%2);
k = (int)(k/2);
}
}
void poly8_bitslice(poly8x64 r, const poly8 x[64])
{
//TODO
int i;
for(i=0;i<64;i++){
poly8 xb[8];
intToBits(x[i], xb);
int j;
long long row;
for(j=0;j<8;j++){
row = row + x[j];
}
printf("row=%d \n", row);
}
}
int main()
{
poly8 a[64], b[64], r[64];
poly8x64 va, vb, vt;
int i;
FILE *urandom = fopen("/dev/urandom","r");
for(i=0;i<64;i++)
{
a[i] = fgetc(urandom);
b[i] = fgetc(urandom);
}
poly8_bitslice(va, a);
poly8_bitslice(vb, b);
fclose(urandom);
return 0;
}
I am not sure I fully understood your question but you can do something like this
char ch0 = 0xAA;
char ch1 = 0xBB;
char ch2 = 0xCC;
char ch3 = 0xDD;
long long int x = 0; // x is 0x00000000
x = (long long int)ch0; // x is 0x000000AA
x = x << 8; // x is 0x0000AA00
x = x | (long long int)ch1; // x is 0x0000AABB
x = x << 8; // x is 0x00AABB00
x = x | (long long int)ch2; // x is 0x00AABBCC
x = x << 8; // x is 0xAABBCC00
x = x | (long long int)ch3; // x is 0xAABBCCDD
In this case x would contain 0xAABBCCDD
The << operator will shift the content of the left hand operator by the number specified by the right hand operator. So 0xAA << 8 would become 0xAA00. Note that it will append zeros at the end while shifting.
The| operator will perform a bitwise or on both its operands. That is a bit by bit or. So the first bit of the left hand operator will be or'ed with the first bit of the right hand operator and the result will be placed in the first bit of the result.
Anything or'ed with zero results to its self so
0xAA00 | 0x00BB
would result in
0xAABB
In general a bit append function would be
long long int bitAppend(long long int x, char ch) {
return ((x << 8) | (long long int)ch);
}
This function would take the long long integer that you need to append to and the char to append to it and would return the appended long long int. Note that as soon as the 64 bits are filled up the high order bits will be shifted out.
For example
long long int x = 0x1122334455667788
x = x << 8; // x now is 0x2233445566778800
this would result into x being 0x2233445566778800 since there is only 64bits in a long long int so the high order bits had to move out.

Read an int value using a char pointer and return it

static unsigned int read24(unsigned char *ptr)
{
unsigned int b0;
unsigned int b1;
unsigned int b2;
unsigned int b3;
b0 = *ptr++;
b1 = *ptr++;
b2 = *ptr++;
b3 = *ptr;
return ( ((b0 >> 24) & 0x000000ff) |
((b1 >> 8) & 0x0000ff00) |
((b2 << 8) & 0x00ff0000) |
(b3 << 24) & 0x00000000 // this byte is not important so make it zero
);
}
Here i have written a function and am trying to read 32 bits (4bytes) using a char pointer and return those 32 bits (4bytes).I have a doubt if this will work properly.Also,am i using/wasting too much memory by defining 4 different integer variables?Is there a better way to write this function. Thank you for your time.
First, drop b3, since you're apparently meaning to read 24 bits you shouldn't even try to access that extra byte (what if it's not even allocated?).
Second, I think you have your shifts wrong. b0 will always be in the range [0..255], so if you >> 24, it'll become zero. There's also no need to mask anything out, since you're coming from unsigned char you know you'll only have 8 bits set. You probably want either:
return (b0 << 16) | (b1 << 8) | b2;
or
return (b2 << 16) | (b1 << 8) | b0;
depending on the endianness of your data.
As for using those intermediate ints, if you have a decent compiler it won't matter (the compiler will optimize them out). If however you're writing for an embedded platform or otherwise have a less-than state of the are compiler, it's possible that eliding the intermediate ints may help your performance. In this case, don't put multiple ptr++s in the same statement, use ptr[n] instead to avoid undefined behavior from multiple increments.
Well, I'm not too clear on what you're attempting to do. If I'm not mistaken you want to input a char* (Most likely 4 bytes if you're running a 32 bit system) and get the same organization of bytes as an int* (4 bytes)
If all you want is the int* version of a char* set of bytes you can use type-casting:
unsigned int* result = (unsigned int*)ptr;
If you want the same collection of bytes BUT you want the most significant byte to be equal to 0 then you can do this:
unsigned int* result = (unsigned int*)ptr & 0x0FFF;
Some additional info:
-Type Casting is a method of temporarily "casting" a variable as any type you want via the use of a temporary copy that is of the type your casting the variable to You can make a variable act as any type you want if you typecast it:
Example:
unsigned int varX = 48;
//Prints "Ascii decimal value 48 corresponds with: 0"
printf ("Ascii decimal value 48 corresponds with: %c\n", (char)varX);
-Hexidicamal digits occupy one byte each. So in your code:
0x000000ff -> 8 bytes of data
0x implies that each of the place holders are a hexidecimal value and
I think what you were going for was 0x000F, which would make all the other bytes 0 except the least significant byte
ANSI-C can process hexidecimal(prefix -> 0x), octal(prefix -> 0) and decimal
Hope this helped!
When building your number from the individual pointers, you must shift the numbers to the left as you incrementally Or the values together. (for little endian machines). Think of it this way, after you read b0, that will be the least significant byte in your final number. Where do more significant bytes go? (to the left).
When you read a pointer value into b0, b1, b2, b3, all they hold is one byte each. They have no way of knowing where they came from in the original number, so there is no "relative" shifting required. You just start with the least significant byte, and incrementally shift each successive byte to the left by 1 byte more than the last.
Below, I have used all bytes in the building of the unsigned value from the unsigned char pointers as an example. You can simply omit bytes you do not need to meet your needs.
#include <stdio.h>
#include <stdlib.h>
#if defined(__LP64__) || defined(_LP64)
# define BUILD_64 1
#endif
#ifdef BUILD_64
# define BITS_PER_LONG 64
#else
# define BITS_PER_LONG 32
#endif
char *binstr (unsigned long n);
static unsigned int read24 (unsigned char *ptr);
int main (void) {
unsigned int n = 16975631;
unsigned int o = 0;
o = read24 ((unsigned char *)&n);
printf ("\n number : %u %s\n", n, binstr (n));
printf (" read24 : %u %s\n\n", o, binstr (o));
return 0;
}
static unsigned int read24 (unsigned char *ptr)
{
unsigned char b0;
unsigned char b1;
unsigned char b2;
unsigned char b3;
b0 = *ptr++; /* 00001111000001110000001100000001 */
b1 = *ptr++; /* b0 b1 b2 b3 */
b2 = *ptr++; /* b3 b2 b1 b0 */
b3 = *ptr; /* 00000001000000110000011100001111 */
return ((b0 & 0x000000ffU) |
((b1 << 8 ) & 0x0000ff00U) |
((b2 << 16) & 0x00ff0000U) |
((b3 << 24) & 0xff000000U));
}
/* simple return of binary string */
char *binstr (unsigned long n)
{
static char s[BITS_PER_LONG + 1] = {0};
char *p = s + BITS_PER_LONG;
if (!n) {
*s = '0';
return s;
}
while (n) {
*(--p) = (n & 1) ? '1' : '0';
n >>= 1;
}
return p;
}
Output
$ ./bin/rd_int_as_uc
number : 16975631 1000000110000011100001111
read24 : 16975631 1000000110000011100001111
Consider using the following approach for your task:
#include <string.h>
unsigned int read24b(unsigned char *ptr)
{
unsigned int data = 0;
memcpy(&data, ptr, 3);
return data;
}
This is for case if you want direct order of bits, but I suppose you do not...
Concerning your code - you must apply mask and then make shift, e.g.:
unsigned int read24(unsigned char *ptr)
{
unsigned char b0;
unsigned char b1;
unsigned char b2;
b0 = *ptr++;
b1 = *ptr++;
b2 = *ptr;
return ( (b0 & 0x0ff) >> 16 |
(b1 & 0x0ff) >> 8 |
(b2 & 0x0ff)
);
}

Using bit packing to mimic functionality of 3d array in c

I have a 3d boolean array of the following dimensions:
bool myArray[streamCount][dayCount][minuteCount];
where
dayCount = 500, streamCount = 11,000 and minuteCount = 400;
I am trying to dramatically shrink the memory requirements of this array by using bit packing.
I need to retain the ability to randomly access any of the values, in the same way I do now with the 3d array.
Below is the (brain-dead) scheme I devised. It has the problem that to find the value, I need to set up
8 if statements. Is there an easier way to do this?
#define STREAM_COUNT 11000
#define DAY_COUNT 500
typedef struct s_minuteStorage
{
unsigned char a: 1;
unsigned char b: 1;
unsigned char c : 1;
unsigned char d : 1;
unsigned char e: 1;
unsigned char f: 1;
unsigned char g : 1;
unsigned char h : 1;
} minuteStorage;
typedef struct s_itemStorage
{
minuteStorage Minutes[STREAM_COUNT][50];
} itemStorage;
itemStorage *Items;
void allocStorage(void)
{
Items = (itemStorage *) ecalloc(DAY_COUNT, 1);
}
int getMinuteValue(int minuteIndex, int dayIndex, int streamIndex)
{
int minuteArrayIndex = minuteIndex / 8;
int remainder = minuteIndex % 8;
int value;
if (remainder == 0)
value = Items[dayIndex].Minutes[streamIndex][minuteArrayIndex].a;
if (remainder == 1)
value = Items[dayIndex].Minutes[streamIndex][minuteArrayIndex].b;
if (remainder == 2)
value = Items[dayIndex].Minutes[streamIndex][minuteArrayIndex].c;
// etc
return(value);
}
Instead of using a struct, you can just use an unsigned char and shift by the proper number of bits:
typedef unsigned char minuteStorage;
int getMinuteValue(int minuteIndex, int dayIndex, int streamIndex)
{
int minuteArrayIndex = minuteIndex / 8;
int remainder = minuteIndex % 8;
minuteStorage m = Items[dayIndex].Minutes[streamIndex][minuteArrayIndex];
return (m >> remainder) & 1;
}

unsigned to hex digit

I got a problem that says: Form a character array based on an unsigned int. Array will represent that int in hexadecimal notation. Do this using bitwise operators.
So, my ideas is the following: I create a mask that has 1's for its 4 lowest value bits.
I push the bits of the given int by 4 to the right and use & on that int and mask. I repeat until (int != 0). My question is: when I get individual hex digits (packs of 4 bits), how do I convert them to a char? For example, I get:
x & mask = 1101(2) = 13(10) = D(16)
Is there a function to convert an int to hex representation, or do I have to use brute force with switch statement or whatever else?
I almost forgot, I am doing this in C :)
Here is what I mean:
#include <stdio.h>
#include <stdlib.h>
#define BLOCK 4
int main() {
unsigned int x, y, i, mask;
char a[4];
printf("Enter a positive number: ");
scanf("%u", &x);
for (i = sizeof(usnsigned int), mask = ~(~0 << 4); x; i--, x >>= BLOCK) {
y = x & mask;
a[i] = FICTIVE_NUM_TO_HEX_DIGIT(y);
}
print_array(a);
return EXIT_SUCCESS;
}
You are almost there. The simplest method to convert an integer in the range from 0 to 15 to a hexadecimal digit is to use a lookup table,
char hex_digits[] = "0123456789ABCDEF";
and index into that,
a[i] = hex_digits[y];
in your code.
Remarks:
char a[4];
is probably too small. One hexadecimal digit corresponds to four bits, so with CHAR_BIT == 8, you need up to 2*sizeof(unsigned) chars to represent the number, generally, (CHAR_BIT * sizeof(unsigned int) + 3) / 4. Depending on what print_array does, you may need to 0-terminate a.
for (i = sizeof(usnsigned int), mask = ~(~0 << 4); x; i--, x >>= BLOCK)
initialising i to sizeof(unsigned int) skips the most significant bits, i should be initialised to the last valid index into a (except for possibly the 0-terminator, then the penultimate valid index).
The mask can more simply be defined as mask = 0xF, that has the added benefit of not invoking undefined behaviour, which
mask = ~(~0 << 4)
probably does. 0 is an int, and thus ~0 is one too. On two's complement machines (that is almost everything nowadays), the value is -1, and shifting negative integers left is undefined behaviour.
char buffer[10] = {0};
int h = 17;
sprintf(buffer, "%02X", h);
Try something like this:
char hex_digits[] = "0123456789ABCDEF";
for (i = 0; i < ((sizeof(unsigned int) * CHAR_BIT + 3) / 4); i++) {
digit = (x >> (sizeof(unsigned int) * CHAR_BIT - 4)) & 0x0F;
x = x << 4;
a[i] = hex_digits[digit];
}
Ok, this is where I got:
#include <stdio.h>
#include <stdlib.h>
#define BLOCK 4
void printArray(char*, int);
int main() {
unsigned int x, mask;
int size = sizeof(unsigned int) * 2, i;
char a[size], hexDigits[] = "0123456789ABCDEF";
for (i = 0; i < size; i++)
a[i] = 0;
printf("Enter a positive number: ");
scanf("%u", &x);
for (i = size - 1, mask = ~(~0 << 4); x; i--, x >>= BLOCK) {
a[i] = hexDigits[x & mask];
}
printArray(a, size);
return EXIT_SUCCESS;
}
void printArray(char a[], int n) {
int i;
for (i = 0; i < n; i++)
printf("%c", a[i]);
putchar('\n');
}
I have compiled, it runs and it does the job correctly. I don't know... Should I be worried that this problem was a bit hard for me? At faculty, during exams, we must write our code by hand, on a piece of paper... I don't imagine I would have done this right.
Is there a better (less complicated) way to do this problem? Thank you all for help :)
I would consider the impact of potential padding bits when shifting, as shifting by anything equal to or greater than the number of value bits that exist in an integer type is undefined behaviour.
Perhaps you could terminate the string first using: array[--size] = '\0';, write the smallest nibble (hex digit) using array[--size] = "0123456789ABCDEF"[value & 0x0f], move onto the next nibble using: value >>= 4, and repeat while value > 0. When you're done, return array + size or &array[size] so that the caller knows where the hex sequence begins.

Resources