Python如何将整数转化成二进制字符串

Python 如何将整数转化成二进制字符串

1、你可以自己写函数采用 %2 的方式来算。

>>> binary = lambda n: ‘‘ if n==0 else binary(n/2) + str(n%2)
>>> binary(5)
‘101‘
>>>

2、采用 python 自带了方法 bin 函数,比如 bin(12345) 回返回字符串 ‘0b11000000111001‘, 这个时候在把0b去掉即可:

>>> bin(12345).replace(‘0b‘,‘‘)
‘11000000111001‘

3、也可以采用字符串的 format 方法来获取二进制:

>>> "{0:b}".format(12345)
‘11000000111001‘
>>>

原文地址:https://www.cnblogs.com/dyhao/p/10126808.html

时间: 2024-08-28 13:06:16

Python如何将整数转化成二进制字符串的相关文章

Python整数转成二进制字符串

1 def Int2Binary(n): 2 res="" 3 s=n/2 4 y=n%2 5 while(s>0): 6 res=str(y)+res 7 temp=s 8 s=temp/2 9 y=temp%2 10 res="1"+res 11 return res

【读书笔记】C Primer Plus ch.15位运算 示例程序15.1 整数转换成二进制字符串

正文: https://www.zybuluo.com/RayChen/note/595213

iOS开发之---将时间戳,转化成时间字符串。

1.将一个NSDate,转化成时间字符串. NSDate *date = [NSDate date]; NSDateFormatter *fmt = [[NSDateFormatter alloc] init]; fmt.dateFormat = @"yyyy-MM-dd"; NSString *dateStr = [fmt stringFromDate:date];

十进制转化成二进制

众多程序 其实就是自己平时的算法转化成计算机的语言 1 #include<stdio.h> 2 3 //十进制转化成二进制 4 5 int main() 6 { 7 int a,b[100],c; 8 int i,j; 9 printf("please enter the number :"); 10 scanf("%d",&a); 11 j=0; 12 for(i=1;i<=a/2;i++) 13 { 14 15 while(a) 16

[LeetCode] Integer to Roman 整数转化成罗马数字

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. 之前那篇文章写的是罗马数字转化成整数(http://www.cnblogs.com/grandyang/p/4120857.html), 这次变成了整数转化成罗马数字,基本算法还是一样.由于题目中限定了输入数字的范围(1 - 3999), 使得题目变得简单了不少. 基本字符 I V

Educational Codeforces Round 80 (Rated for Div. 2)【A,B,C,D】C题DP{GG了} D题【数组转化成二进制形式判断+二分】

A题直接暴力水过 1 #include<bits/stdc++.h> 2 3 using namespace std; 4 #define int long long 5 #define N 6666666 6 int arr[N]; 7 8 signed main(){ 9 int _;cin>>_; 10 while(_--){ 11 int n,m; 12 cin>>n>>m; 13 if(n>=m){ 14 cout<<"

计算十进制数转化成二进制时1的个数

#include <iostream> using namespace std; int func(int x) { int cnt = 0; while (x) { cnt++; x = x&(x - 1); } return cnt; } int main() { cout << func(9999) << endl << func(8); cin.get(); return 0; } 输出8,1 其实上面那个函数输出结果是:形参x转化为二进制后

C语言获取系统当前时间转化成时间字符串

因为保存的文件须要加上保存的时间,所以须要一个函数来将系统当前时间获取出来,同一时候转换成时间字符串.详细的时间代码例如以下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 #include <stdio.h> #include <time.h> int getNowTime(char

十进制如何转化成二进制,返回字符串形式

def Dec2Bin(num): temp = [] result = '' while num: yushu = num % 2 num = num//2 temp.append(yushu) while temp: result += str(temp.pop()) return result print(Dec2Bin(25))======11001 temp是一个空列表,用来保存每次除2后的余数 result是一个空的字符串,用以输出二进制的字符串形式 append()将余数添加到列表