Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python equivalent for char datatype in C

Tags:

python

is there any python datatype equivalent to char datatype in C? in C, a char variable can store only 1 byte of information. for eg the C code and its output

void main()
{
   char a;
   printf("Enter the value");
   scanf("%d",&a);
   printf("A = %d",a);
}

output

Enter the value 255
A = 255

Enter the value 256
A = 0

I want the exact output in python. please help me. thanks in advance.

like image 412
reshmi g Avatar asked Sep 19 '25 09:09

reshmi g


2 Answers

Given your usecase is that you want modular behaviour, just take your input as an int, and do a%256 to find the result you want.

like image 157
Marcin Avatar answered Sep 22 '25 00:09

Marcin


Marcin's answer is probably want you wanted based on your question, and vorac's answer has another way, but since I started to type this: Note that python does have a struct library that would also allow you to manipulate things as bytes, shorts, etc.

Example:

import struct
import socket
s = socket.socket()
s.connect("127.0.0.1",5000)  # connect to some TCP based network (and ignore any sort of endiness issues, which could be solved with other arguments to struct.pack)
data1 = 100
data2 = 200
data_packed = struct.pack("cc",chr(data1),chr(data2)) # pack 2 numbers as bytes (chars)
s.send(data_packed) # put it on the network as raw bytes
data_packed_out = s.recv(100) # get raw bytes from the network
data3,data4 = struct.unpack("cc",data_packed_out) # unpack said bytes
like image 34
Foon Avatar answered Sep 22 '25 00:09

Foon