Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C convert long integer to bytes (binary) #144

Open
aben20807 opened this issue Mar 21, 2023 · 0 comments
Open

C convert long integer to bytes (binary) #144

aben20807 opened this issue Mar 21, 2023 · 0 comments
Labels
catg:C catg:PL Programming Language

Comments

@aben20807
Copy link
Owner

https://godbolt.org/z/qzq4jWK6P

#include <stdio.h>
#include <string.h>

void longtobin1(unsigned long n) {
    char str[9];
	snprintf(str,8, "%c%c%c%c%c%c%c%c", 
    (unsigned char)((n >> 0) & 0xFF),
    (unsigned char)((n >> 8) & 0xFF),
    (unsigned char)((n >> 16) & 0xFF),
    (unsigned char)((n >> 24) & 0xFF),
    (unsigned char)((n >> 32) & 0xFF),
    (unsigned char)((n >> 40) & 0xFF),
    (unsigned char)((n >> 48) & 0xFF),
    (unsigned char)((n >> 56) & 0xFF));
	for (int i = 0; i < 8; i++) {
		printf("%c", str[i]);
	}
}

void longtobin2(unsigned long n) {
    union {
        unsigned long i;
        char s[8];
    }x = {n};
	for (int i = 0; i < sizeof(n); i++) {
		printf("%c", x.s[i]);
	}
}

void longtobin3(unsigned long n) {
    char s[sizeof(n)];
    memcpy(s, &n, sizeof(n));
	for (int i = 0; i < sizeof(n); i++) {
		printf("%c", s[i]);
	}
}

int main(int argc, char *argv[]) {
	unsigned long n = 201339578400;
	longtobin1(n);
    longtobin2(n);
    longtobin3(n);
    return 0;
}
@aben20807 aben20807 added catg:PL Programming Language catg:C labels Mar 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
catg:C catg:PL Programming Language
Projects
None yet
Development

No branches or pull requests

1 participant