c - Bitwise Concatenation -
i have following:
char *pointer = decimal_to_binary(192) // yields 11000000 char *pointer2 = decimal_to_binary(168) // yields 10101000
i trying concat them into:
1100000010101000
i referencing: concatenate binary numbers of different lengths , using:
unsigned long pointer3 = (*pointer << 16) | *pointer2;
which gives output:
1100010000000000110001
what doing wrong?
you don't show how print anything, makes difficult interpret question. however, statement irretrievably broken in nothing concatenate strings pointed @ pointer
, pointer2
:
unsigned long pointer3 = (*pointer << 16) | *pointer2;
this takes first character pointer
points @ (a 1
) , shifts value left 16 bits, , adds (ors) in first character pointer2
points @ (another 1
), , assigns integer format misnamed pointer3
. thus, gets value:
pointer3 = 0x00310031;
the question takes interpretation, making plausible (but not accurate) assumptions, code might you're after:
#include <stdio.h> #include <stdlib.h> #include <string.h> static char *decimal_to_binary(unsigned char byte) { char *result = malloc(9); if (result != 0) { char *digit = result; (int = 0; < 8; i++) *digit++ = ((byte >> (7 - i)) & 0x01) + '0'; *digit = '\0'; } return result; } int main(void) { char *pointer1 = decimal_to_binary(192); char *pointer2 = decimal_to_binary(168); char concatenated[17]; unsigned long pointer3 = (*pointer1 << 16) | *pointer2; strcpy(&concatenated[0], pointer1); strcpy(&concatenated[8], pointer2); printf("p1 = <<%s>>; p2 = <<%s>>; p3 = 0x%08lx; c = <<%s>>\n", pointer1, pointer2, pointer3, concatenated); free(pointer1); free(pointer2); return(0); }
output:
p1 = <<11000000>>; p2 = <<10101000>>; p3 = 0x00310031; c = <<1100000010101000>>
note code using decimal_to_binary()
not take care avoid (mis)using null pointers. design of decimal_to_binary()
less stellar; free()
calls forgotten. better design be:
void decimal_to_binary(unsigned char byte, char buffer[9]);
where calling code provides buffer binary output written. there other ways of writing loop in decimal_to_binary()
; might more efficient 1 chosen here.
Comments
Post a Comment