How to get memory address in C and output it? - c

I need to get memory address and bits of index then I need to output index of the memory address. Can anyone help?

Given any variable in C, you can get its address using the "address-of" operator &:
int x;
int* addressOfX = &x;
You can print out addresses using the %p specifier in printf:
printf("%p\n", &x); // Print address of x
To access individual bits of an integer value, you can use the bitwise shifting operators, along with bitwise AND, to shift the bit you want to the proper position and then to mask out the other bits. For example, to get the 5th bit of x, you can write
int x;
int fifthBit = (x >> 4) & 0x1;
This shifts down the number 4 bits, leaving the fifth bit in the LSB spot. ANDing this value with 1 (which has a 1 bit in the lowest spot and 0 bits everywhere else) masks out the other bits and returns the value. For example:
int x = 31; // 11111
prtinf("%d\n", (x >> 4) & 0x1); // Prints 1

This worked for me ;)
// uses :: head
// ----------------------------------------------
#include <stdio.h>
// ----------------------------------------------
// func :: main
// ----------------------------------------------
int main()
{
void *fooz = "bar";
char addr[64];
sprintf(addr, "%p", &fooz);
// do some stuff with `addr`, or not :)
puts(addr);
return 0;
}
// ----------------------------------------------
Prints out something like: ~> 0x7ffdfb91d698

Related

set bin field in an array based on offset and length

I want to develop a function in C that set a binary field in array starting from a given offset and finish with a given length.
For example, my binary array is:
01101011 10010101 11001011 11010001 11000101 00101011
the buffer used for set:
10011001 01011011 10100010
So if the offset = 5 and the length = 7, the result will be
we will set the 7 first bit from the set buffer (1001100) in the binary buffer starting from the offset 5:
01101100 11000101 11001011 11010001 11000101 00101011
^ ^
| |__End of set field (len=7)
offset=5
Are there predefined algorithms for that? using bitwise operators?
Given char * arrays, you can easily implement operators set and get to set and retrieve, respectively, the i-th bit:
void set(char *a, int position, int value) {
int byte = position >> 3;
int bit = 1 << (position & 0x07); // 00000001b to 10000000b
a[byte] = value ?
a[byte] | bit : // on
a[byte] & ~bit; // off
}
int get(char *a, int position) {
return a[position>>3] & (1 << (position&0x07)) ? 1 : 0;
}
This can be made slightly faster with compiler intrinsics to get both division and modulus at the same time, and there is probably some bitwise trick to avoid branching in 'set' - but hopefully this code communicates the gist of the operation.
Implementing your desired function is essentially an extension of the code in my set function, where instead of only touching one bit, you continue until you run out of bits to modify, starting at the indicated offset.
Edit: adding a bitwise trick from this answer to remove branching from set:
void set(char *a, int position, int value) {
int byte = position >> 3;
int offset = position & 0x07);
a[byte] = (a[byte] & ~(1<<offset)) | (value<<offset);
}
Note that this version requires value to be either 0 or 1; the previous version would work with any false or true (=zero vs. non-zero) value.

Flipping certain bit in an integer (C language)

I'm trying to get my program to work where a certain bit is being flipped. I have this function called flipbit(int *p, int m). The user needs to input a digit and a bit number. Let's say the user gives the number 8 (00001000) and the bit number 2, so the 2nd bit in 8 should be flipped, which becomes 00001010. How can I program this?
EDIT: I made a stupid mistake, I want to count starting from 0, so the 2nd bit in 8 flipped is actually 00001100 instead of 00001010.
#include <stdio.h>
#include <stdlib.h>
void flipbit(int *p, int m) {
int digit;
digit = *p;
int bit;
bit = &m;
int result;
//printf("The numbers are %d %d", digit, bit);
printf("%d", result);
}
int main() {
int number1;
int number2;
printf("Give number and bit: ");
scanf("%d, %d",&number1, &number2);
flipbit(&number1, &number2);
return 0;
}
Given the bit to flip, you first need to create a mask. Do that by taking the value 1 and left shifting it by the bit number.
Once you have that mask, use the bitwise XOR operator ^ to flip the bit.
int mask = 1 << m;
*p = *p ^ mask;
When checking your source code, there are mixture between pointer and value.
To comply the call of your flipbit() function with the declaration, the call should be:
// first parameter is a pointer and second parameter is a value
flipbit(&number1, number2); // void flipbit(int *p, int m);
Inside the flipbit() function, the mixture continues because digit is a value and p is a pointer. The code should be:
int digit;
// 'digit' is a value and 'p' is a pointer
digit = p[0]; // 'digit' is the first value pointed by 'p'
Same error kind of error with the 'bit' parameter
int bit;
// 'bit' is a value and 'm' is a value
bit = m;
And the result to flip a bit is the XOR operation.
the bit number 2, so the 2nd
Due to your specification, you have to shift only of (bit - 1).
So, in your case:
0x0001(or 0000.0000.0000.0001b) << (2 - 1) = 0x0002(or 0000.0000.0000.0010b)
result is 0x0010(or 0000.0000.0000.1000b) XOR 0x0002(or 0000.0000.0000.0010b) = 0x0012(or 0000.0000.0001.0010b).
int result;
result = digit ^ (0x0001 << (bit - 1));
Did you enter '9, 1' to comply with the scanf("%d, %d",..) ?

Storing int value into char p[] index

Been stuck on a problem. figured out my issue. I have looked online quite a bit and have read many possible solutions, but nothing seems to work for me.
I have this program, lets call it test.c
#include <stdio.h>
int main() {
int x = 21345;
char p[10];
p[0] = x;
printf("%d\n", x);
printf("%d", p[0]);
return 0;
}
As you would guess, I want the two printf statements to have the same output. Instead, I get the following output...
21345
97
I need 21345 to be at p[0], and when I call printf("%d", p[0]);
It needs to print out 21345, not 97
Any help? :(
EDIT:
Looks like you guys answered, thanks! Changing to int p[10] would solve the problem. I have another complication though, I also need to be able to store strings inside the indexes of p, along with ints.. how should I tackle this?
A char does not have the same type as int and is not identical in number of bits. You would need int p[10]; for that to work.
You have an array of signed chars, they take 1 byte each, the max value would be 127 and minimum -128. Now the x's value takes more bytes to represent, there is an overflow, and it truncates the leftmost bits,
21345 has the binary representation: 0101 0011 0110 0001
now discard the leftmost byte and you get: 0110 0001 which is 97
char store only 1 byte value so that you are getting that output. If you change char p[10] to int p[10] you will get output.
char is simply not big enough to store 21345. Therefore compiler takes just low 8 bits and puts them into char, so it becomes 97. When passing to printf it will convert it back to int but the highest bits are already lost.
You need to use int array instead of char
It should be like
#include <stdio.h>
int main() {
int x = 21345;
int p[10];
p[0] = x;
printf("%d\n", x);
printf("%d", p[0]);
return 0;
}
Output
21345
21345
Well if you want to use same array for strings too, use 2 dimensions char array
because you can store a integer value in 4 characters array correctly.
so you need to use p[10][4]
Now store each byte of int in corresponding char array index
p[0][0] = (x >> (8*0)) & 0xff;
p[0][1] = (x >> (8*1)) & 0xff;
p[0][2] = (x >> (8*2)) & 0xff;
p[0][3] = (x >> (8*3)) & 0xff;

C bit-wise operations with hex numbers

Is there a way to access certain parts of a hexadecimal number in C?
I want to write a function that takes in a hexadecimal number and negates it, but leaves the least significant byte unchanged. Example: 0x87654321 should become 0x789ABC21.
I've tried to somehow save the LSB and then apply it to the negated x, but my problem is that my mask gets applied to all bytes. I could hard code it for a specific value, but obviously that's not what I want.
void b(int x) {
int temp = x & 0xFF; // temp is all 0 with the LSB being the same as x's
x = ~x; // this negates x
// one of a couple of attempts I tried thus far:
// x = (x & 0x00) | temp;
// idea: change x's LSB to 00 and OR it with temp,
// changing x's LSB to temp's LSB
}
I'd appreciate if you don't post code for the solution, but rather just answer whether there is a way to apply bit operations to specific sections of a hexadecimal number, or how I could possibly solve this.
In general you can operate on specific bits of a value by using a mask.
A mask is bit-pattern with 1s where you want to operate and 0s where you don't.
It seems like you need 3 operations: extract lowest byte, negate, restore lowest byte. You can figure out negation, so I'll just talk about extracting a bit-field and restoring an extracted bit-field.
To extract specified bits, use a mask with 1s for the desired bits and use the bitwise and operator &. The and operator sets 0s for all 0s of the mask, and where the mask is 1, it copies the bits from the other argument. If you need to examine this value elsewhere in your program, it may also be convenient to right-shift >> the value down to the lowest position (so it's easier to lookup in tables).
To restore saved bits, shift back up if you shifted it down earlier. Then clear those bits from the value, and use inclusive-or | as a bitwise sum of all one bits. To clear the bits from the value, use the inverse of the mask from the first operation. Ie. y = x & 0xf saves a nibble, x & ~0xf clears that nibble, (x & ~0xf) | y recombines to the same original x.
Edit:
If the piece you're extracting is not in the lowest position, say the second byte (LSB) from a 32 bit unsigned integer, then it may be useful to shift the extracted value to the zero position to work with it.
x = 0x12345678;
y = x & 0xFF00; // == 0x5600
y >>= 8; // == 0x56
But if you do this then you have to shift it back to the correct position (of course) before updating the larger value with a new value for the bitfield.
x = (x & ~0xFF00) | (y << 8);
If I correctly understood the question, seems like it would be something like this (untested).
void b(int x) {
return (~x & ~0xFF) | (x & 0xFF);
}
I've found a way to manipulate a chosen byte. (!!! This would be homework 2.60 of CS:APP !!!)
If 0x12345678 is a given hexadecimal value of type, say int, then doing this will allow me to change the ith byte:
int x = 0x12345678;
unsigned char* xptr = (unsigned char*) &x;
xptr[i] = 0; // say i=2, then this would yield: 0x120045678
Now, if I want to add a value in the position of byte i, say 0xAB, I'd do what luser droog already mentioned:
int temp = 0xAB;
temp = temp << i*8; // say i=2, then this would yield: 0x00AB0000
x = x | temp; // this yields the desired result 0x12AB3456

Left Bit Shift In C without extension

I was wondering how to get C to not extend my binary number when I bitshift to the left
int main ()
{
unsigned int binary_temp = 0b0100;
binary_temp = binary_temp << 2;
printf("%d", binary_temp);
return 0;
}
When I run that I want a return value of 0 since it has extended past the 4 digits I have, but right now it returns 16 (10000). How would I get C not to extend my number?
Edit: I would like to be able to work with the number in binary form so I need to have only 4 digits, and not just outputting the right number.
It does not extend your number but saves it as unsigned int type which is 4 bytes (32 bits) in size. You only fill the last 4 bits. To treat it as only 4 bits, use Bitwise AND with a Mask value. Here's example code:
int main()
{
unsigned int binary_temp = 0b0100;
binary_temp = (binary_temp << 2) & 0b1111;
printf("%u", binary_temp);
return 0;
}
You can bitwise AND the result with a 4 bit mask value:
binary_temp = (binary_temp << 2) & 0xF;
There is no 0b in standard C. You could use 4.
unsigned int /* prepare for wtf identifier: */
binary_temp = 4;
Left shifting by 2 is multiplying by 4. Why not?
binary_temp *= 4;
... and then reduce modulo 16?
binary_temp %= 16;
What sense is there to using binary operators, in this case? I see none.
The %d directive corresponds to an int argument, but the argument you're giving printf is an unsigned int. That's undefined behaviour.
printf("%u", binary_temp);
I'm sure whichever book you're reading will tell you about the %u directive.

Resources