使用动态C程序(语言是C),我试图将一个int转换成一个字节数组--4位长。到目前为止,我已经在网上找到了一些例子。然而,似乎没有人为我工作。在打印正确的字节数时,我遇到了一个持续的问题,但是由于某种原因,它们被重复了两次。我提供了以下守则:
void main(){
int a=1379;
int i=0;
unsigned char value [4];
value[3] = (byte) (a & (0xFF));
value[2] = (byte) ((a >> 8) & 0xFF);
value[1] = (byte) ((a >> 16) & 0xFF);
value[0] = (byte) ((a >> 24) & 0xFF);
//convert int values to bytes by placing them in a char buffer
for(i=0;i<4;i++){
printf("%d",value[i]);
printf(", ");
}
printf("\n");
}
例如,使用这个值,程序打印"5,99,5,99“,而它应该打印"0,0,5,99”。谢谢你的帮助。
发布于 2012-07-11 11:22:11
几乎可以肯定的是,"Dynamic“是一个int
为16位的实现,这对于C来说是完全”合法的“。如果int
是16位,任何超过16位的移位都是模-16,所以第二个移位重复前两个。
发布于 2012-07-11 13:18:15
您需要将int变量中的位复制到char数组中。您可以简单地使用memcpy
这样做:
#include <stdio.h>
#include <string.h>
void split(int val, unsigned char *arr) {
memcpy(arr, &val, sizeof(int));
}
int main() {
unsigned char bytes[4];
split(1379, bytes);
printf("%d, %d, %d, %d\n", bytes[0], bytes[1], bytes[2], bytes[3]);
}
发布于 2012-07-11 11:29:08
#include <stdio.h>
#include <string.h>
int main(void){
int a=1379;
unsigned bot,top ;
unsigned char value [sizeof a];
memcpy (value, &a, sizeof value);
/* You can omit this loop if you are on a big-endian machine */
#if LITTLE_ENDIAN
for (bot =0, top = sizeof value; --top > bot; bot++) {
unsigned char tmp;
tmp = value[bot];
value [bot] = value[top];
value[top] = tmp;
}
#endif
for(bot=0;bot < sizeof value;bot++){
printf("%u", (unsigned int) value[bot]);
printf(", ");
}
printf("\n");
return 0;
}
https://stackoverflow.com/questions/11439700
复制