Judy
Judy

Reputation: 1

Group bits in c

This is a question about c. I already create a mask which is 0xF, but I can's group the digit. Is there anything wrong with my for loop?

void print_hex(void *p)
{
  // copy the value that p points to into an unsigned integer variable.
  unsigned int x = *((unsigned int *) p);

  // In a loop, select four bits at a time using a mask.
  for(int i=0;i<32;i+=4){
    int y = (x >> i)&FOUR_BIT_BASK;
    printf("%d",x);
  }

Upvotes: 0

Views: 185

Answers (2)

mahee96
mahee96

Reputation: 842

The printf function was indeed using x whereas it seems like the intention was to use the variable y.

but on the other note, your printf function assumes size of int to be 32 but on a 64-bit machine where the processor word size is 64-bits and native int is of the size of processor word(essentially 64-bits) you might miss half of the data. As for good coding practice use sizeof(int) when performing such operations.

#include <stdio.h>

void print_hex(void *p){
  // copy the value that p points to into an unsigned integer variable.
  unsigned int x = *((unsigned int *) p);

  const int bits = 8;
  const int nibble = bits/2;
  const int mask = 0xF; //expands to size of int
  // In a loop, select four bits at a time using a mask.
  printf("0x%x", y);
  for(int i=sizeof(int)*bits-nibble; i>=0; i-=nibble){
    int y = (x >> i) & mask;
    printf("%x", y);
  }
}

int x = 511;

void main(){
  print_hex(&x);
}

Output:

0x000001ff

Note: your code prints the bytes in little-endian whereas this code prints it in big endian (also note the %x format specifier in printf, which is used for printing hex values).

Upvotes: 0

selbie
selbie

Reputation: 104559

I suspect it's a typo. The code is printing the value of x, but intends to print y.

Instead of this:

printf("%d",x);

This:

printf("%d",y);

Also, without a space or newline in between print statements, those printed numbers are going to look jumbled together. So maybe this:

printf("%d ",y);

Upvotes: 1

Related Questions