C語言中交換int型變量的值及轉換為字符數(shù)組的方法
更新時間:2016年04月25日 16:00:57 作者:hzy3774
這篇文章主要介紹了C語言中交換int型變量的值及轉換為字符數(shù)組的方法,講解了以不同進制將整型數(shù)字轉換成字符數(shù)組,需要的朋友可以參考下
不使用其他變量交換兩個整型的值:
#include <stdio.h> void main(){ int a = 3; int b = 4; a = a ^ b;//使用異或交換 b = b ^ a; a = a ^ b; printf("%d, %d\n", a, b); a = a - b;//使用加減交換 b = a + b; a = b - a; printf("%d, %d\n", a, b); a ^= b ^= a ^= b; printf("%d, %d\n", a, b); }
整形和字符數(shù)組型轉換:
#include <stdio.h> #include <stdlib.h> int sumof1(int x)//求一個數(shù)轉換成二進制以后1的個數(shù) { int countx = 0; while(x) { countx ++; x &= x-1; //每位與一次x - 1;就能消掉最后一個1 } return countx; } void main(){ char c[10]; int i = 999; itoa(i, c, 10);//以10進制轉換成字符數(shù)組 puts(c); itoa(i, c, 16);//以16進制轉換成字符數(shù)組 printf("0x%s\n", c); itoa(i, c, 8);//以8進制轉換成字符數(shù)組 printf("0%s\n", c); itoa(i, c, 2);//以2進制轉換成字符數(shù)組 puts(c); i = atoi(c);//再將字符串轉成整形 printf("%d\n", i); printf("%d\n", sumof1(i));//以2進制表示時1的個數(shù) }
相關文章
C++實現(xiàn)string存取二進制數(shù)據(jù)的方法
這篇文章主要介紹了C++實現(xiàn)string存取二進制數(shù)據(jù)的方法,針對STL中string的用法進行了較為詳細的分析,需要的朋友可以參考下2014-10-10C語言數(shù)據(jù)(整數(shù)、浮點數(shù))在內存中的存儲
之前對c語言數(shù)據(jù)存儲一直不太明白,最近仔細研究了一番,所以下面這篇文章主要給大家介紹了關于C語言數(shù)據(jù)(整數(shù)、浮點數(shù))在內存中存儲的相關資料,需要的朋友可以參考下2021-06-06全面了解#pragma once與 #ifndef的區(qū)別
下面小編就為大家?guī)硪黄媪私?pragma once與 #ifndef的區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08